Skip to content

🤖 refactor: auto-cleanup#3695

Open
mux-bot[bot] wants to merge 16 commits into
mainfrom
auto-cleanup
Open

🤖 refactor: auto-cleanup#3695
mux-bot[bot] wants to merge 16 commits into
mainfrom
auto-cleanup

Conversation

@mux-bot

@mux-bot mux-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Summary

This is the long-lived auto-cleanup PR. Each run, the auto-cleanup agent reviews new commits merged to main, rebases onto the latest main, and applies at most one extremely low-risk, behavior-preserving cleanup. The branch accumulates a small stack of independent cleanups until it is merged.

Cleanups in this branch

  1. Dedupe memory sweep recordUsage callbacks (MemoryConsolidationService). The consolidation sweep and the harvest sweep each inlined the same 15-line callback that routes billed usage to the headless-usage sidecar and emits analyticsIngest. Extracted into a private makeSweepUsageRecorder(...) helper.
  2. Dedupe the "memory scope is full" cap check (MemoryService). The create and saveFile (new-file) paths each inlined a byte-identical block that called store.listFiles(), compared the count against MEMORY_MAX_FILES_PER_SCOPE, and threw a MemoryCommandError with the same message. Extracted into a private assertScopeHasRoom(store, scope) helper.
  3. Dedupe blockquote line formatting in the bash monitor wake prompt (bashMonitorWakeStore.ts). buildBashMonitorWakePrompt rendered both the matched-output lines and the lost-monitor script with the identical .map((line) => \> ${line}`).join("\n")blockquote pattern in two places. Extracted into a module-levelblockquoteLines(lines)` helper.
  4. Dedupe the tool_search removal in prepareToolSearch (toolCatalog.ts). Both fallback branches (PTC enabled, and empty deferred catalog) inlined the identical { [TOOL_SEARCH_TOOL_NAME]: _removed, ...rest } destructure to drop the built-in tool_search entry from the tool record. Extracted into a module-level withoutToolSearch(tools) helper.
  5. Dedupe the Anthropic cache-create token extraction in accumulateProviderMetadata (usageHelpers.ts). The function inlined the same verbose (metadata.anthropic as { cacheCreationInputTokens?: number } | undefined)?.cacheCreationInputTokens ?? 0 cast twice (once for the accumulated metadata, once for the current step). Extracted into a module-private getAnthropicCacheCreateTokens(metadata) helper.
  6. Dedupe capability-model thinking-policy resolution (thinking/policy.ts). After 🤖 feat: integrate GPT-5.6 Sol/Terra/Luna with native max effort and pro-mode toggle #3708 taught the thinking policy to resolve mappedToModel aliases, both getThinkingPolicyForModel and hasExplicitThinkingPolicy inlined the identical getExplicitThinkingPolicy(resolveModelForMetadata(modelString, providersConfig ?? null)) call. Extracted into a private getExplicitThinkingPolicyForModel(modelString, providersConfig) helper.
  7. Dedupe queue entry clear-callback projection (messageQueue.ts). After 🤖 feat: queue messages behind special sends instead of erroring (FIFO message queue) #3696 rewrote MessageQueue into FIFO QueueEntry items, both getClearCallbacks and removeWorkspaceTurn inlined the identical spread that builds a QueueClearCallbacks object from an entry's optional onCanceled / onAcceptedPreStreamFailure fields. Extracted into a private entryClearCallbacks(entry) helper.
  8. Dedupe the OpenAI-origin model check in openaiExplicitPromptCachingAvailable (cacheStrategy.ts). After 🤖 feat: GPT-5.6 explicit prompt cache breakpoints for direct OpenAI #3712 added the GPT-5.6 explicit-prompt-caching eligibility gate, the function inlined the identical split(":", 2) + origin !== "openai" || !modelName check twice — once for the request model and once for the resolved capability target — and the destructured origin/modelName locals were unused past their guard in both places. Extracted into a module-private isOpenAIOriginModel(canonical) helper.
  9. Dedupe the tool-call-execution-start emit in StreamManager (streamManager.ts). 🤖 fix: start tool elapsed timers when execute() actually runs #3716 introduced the ToolCallExecutionStartEvent, emitted from two places: applyToolExecutionStart (part already stored) and the "tool-call" case that consumes a pendingExecutionStart recorded before the part landed. Both inlined the byte-identical this.emit("tool-call-execution-start", { type, workspaceId, messageId, toolCallId, timestamp } satisfies ToolCallExecutionStartEvent) block, differing only in the toolCallId/timestamp source. Extracted into a private emitToolCallExecutionStart(workspaceId, streamInfo, toolCallId, timestamp) helper.
  10. Dedupe model-parameter extras merge (aiService.ts). After 🤖 feat: apply mid-turn thinking-level changes at the next model step #3718 added mid-turn thinking-level rebuilds, the initial-model path and the fallback-model path each inlined a byte-identical closure (mergeModelParameterExtras / mergeNextModelParameterExtras) that folds providers.jsonc providerExtras UNDER the Mux-built provider-options namespace (short-circuiting when there are no extras, deep-merging via mergeProviderExtrasUnderMux when the namespace is a plain object). The two differed only in the namespace key and the overrides source. Extracted into a module-level makeModelParameterExtrasMerger(namespaceKey, providerExtras) factory that returns the merger closure.
  11. Unify the legacy tool_search part-rename helper (toolCatalog.ts). 🤖 fix: avoid OpenAI tool search name collision #3719 renamed the built-in tool-search tool to tool_catalog_search and added request-time rewriting of historical tool_search call/result parts. It introduced two byte-identical helpers — renameLegacyToolSearchCallPart(part: ToolCallPart) and renameLegacyToolSearchResultPart(part: ToolResultPart) — that differ only in the part type; the rename body is identical. Collapsed both into a single generic renameLegacyToolSearchPart<T extends { toolName: string }>(part: T) and dropped the now-unused ToolCallPart / ToolResultPart imports.
  12. Trim duplicated context-cap rationale comment (codexOAuth.ts). 🤖 fix: cap GPT-5.6 context over Codex OAuth #3724 added the GPT-5.6 family to CODEX_OAUTH_CONTEXT_WINDOW_OVERRIDES and rewrote the map's inline comment with a sentence that restated the rationale already given in the map's doc comment directly above it. Dropped the duplicated rationale sentence, keeping only the tier-specific explanation. Comment-only; no behavior change. (Re-applied on top of [openai] 🤖 fix: use 372K GPT-5.6 OAuth context #3730, which later rewrote the same inline comment and re-introduced the duplicate.)
  13. Dedupe flat-section pinned block resolution (pinnedReorder.ts). 🤖 feat: project-less scratch chats #3723 added a scratch branch to locatePinnedBlock that renders scratch chats as one flat "Chats" section, mirroring the existing multi-project branch. Both branches inlined the byte-identical collectFlatSectionRows(...).filter(isWorkspacePinned).map((row) => row.id) projection, the if (!pinnedIds.includes(meta.id)) return null guard, and the return { fullOrder: pinnedIds, blockIds: pinnedIds } shape — differing only in the includeRow predicate ((row) => row.kind === "scratch" vs isMultiProject). Extracted into a private locateFlatSectionPinnedBlock(meta, sortedWorkspacesByProject, includeRow) helper.
  14. Dedupe JSON-wrapped tool-output unwrap (workflowRunMessages.ts). 🤖 fix: stop terminal workflow await loops #3725 added isTerminalWorkflowRunToolOutput, which re-inlined the byte-identical output.type === "json" && "value" in output container check already used by stripWorkflowRunRecordForModel to detect the { type: "json", value } SDK/UI wrapper before recursing on the inner value. Extracted the check into a module-private isJsonWrappedOutput(output) helper that both functions call, moving the shared rationale into the helper's doc comment. No control flow or return-shape change.
  15. Hoist errorType local in finalizeWorkspaceTurnFromStreamError (taskService.ts). 🤖 fix: keep workspace-turn handles running through auto-retryable stream errors #3729 reworked workspace-turn stream-error settlement, and the reworked function read event.errorType three times and repeated the event.errorType != null guard once for the explicitRecovery computation and once in the recovery if. Hoisted a single const errorType = event.errorType and routed all uses through it, deduplicating the repeated member access and null guard. ErrorEvent is a Zod-inferred plain data type, so the property read has no side effects; pure behavior-preserving simplification with no control-flow change.
  16. Extract buildSkillDescriptor helper for skill discovery (common/orpc/schemas/agentSkill.ts + agent_skill_list.ts + agentSkillsService.ts). 🤖 feat: skills refresh — invocation control, $ARGUMENTS, dynamic context, .claude compat #3728 (skills refresh) added user-invocable / argument-hint / when_to_use frontmatter and normalized them via resolveSkillAdvertise / resolveSkillUserInvocable / resolveSkillWhenToUse. Both descriptor-building sites — readSkillDescriptor (the agent_skill_list tool) and readSkillDescriptorFromDir (agentSkillsService discovery) — then inlined the byte-identical 7-field object literal mapping parsed.frontmatter + scope into an AgentSkillDescriptor before AgentSkillDescriptorSchema.safeParse. Extracted the mapping into a shared buildSkillDescriptor(frontmatter, scope) in agentSkill.ts (co-located with the resolveSkill* helpers it calls) and dropped the now-unused resolveSkill* imports at both call sites. Callers still run safeParse themselves since they handle validation failure differently. No behavior change.

This run

Considered origin/main from the previous checkpoint 83a6264ae through 0d7d0893d (HEAD), covering the three new commits merged since the last run:

Validation

  • Rebased cleanly onto origin/main (0d7d0893d); all prior cleanups replayed without conflict and the branch merges cleanly into main.
  • make static-check passes for ESLint, both TypeScript configs, and Prettier. (The shell formatter shfmt is not installed in this environment; the change is TypeScript-only and touches no shell files.)
  • bun test passes (60/60) for the affected suites — agentSkillsService.test.ts, agent_skill_list.test.ts, and parseSkillMarkdown.test.ts — exercising both descriptor-construction paths through the new helper.

Risks

Very low. Each cleanup is a behavior-preserving simplification that extracts byte-identical inlined logic into a helper (or, for #15, hoists a repeated side-effect-free property read into a local) — no control flow, arguments, thresholds, error types, emitted events, validation, or rendered text change. Cleanup #16 adds a helper in the shared skill-schema module consumed by both discovery paths; both call sites still validate via AgentSkillDescriptorSchema.safeParse, so descriptor output is unchanged. The sole comment-only cleanup (#12) touches no executable code.

Auto-cleanup checkpoint: 0d7d089


Generated with mux • Model: anthropic:claude-opus-4-8 • Thinking: xhigh • Cost: $0.00

@mux-bot

mux-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from a2454d3 to 450337d Compare July 8, 2026 17:01
@mux-bot

mux-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

⚠️ Auto-fixup: CI failure appears to be infrastructure/flaky, not caused by this cleanup commit — no code pushed.

Root cause: The Static Checks job failed with the runner annotation "The self-hosted runner lost communication with the server" after running the full 10m, and its log blob was never uploaded (BlobNotFound). Test / Integration was cancelled and Required failure are both downstream of that (Required only aggregates results).

Verification: Ran make static-check locally on this PR's HEAD (a2454d31b). ESLint, both TypeScript configs (tsgo --noEmit ×2), and Prettier all pass. The only local miss is fmt-shell-check because shfmt isn't installed in the fixup sandbox — and this PR changes no shell files, so it's irrelevant.

Recommendation: Re-run the failed CI jobs. No code change needed.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from 450337d to e32952d Compare July 9, 2026 00:30
@mux-bot

mux-bot Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

Latest push rebases onto origin/main (through #3698) and adds one low-risk, behavior-preserving cleanup: extract the duplicated per-scope "memory scope is full" cap check in MemoryService.create / saveFile into a private assertScopeHasRoom(store, scope) helper. No control flow, thresholds, error types, or events change. make static-check (ESLint + both tsconfigs + Prettier) and bun test memoryService.test.ts (75/0) pass locally.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from e32952d to d8d0ba5 Compare July 9, 2026 09:10
@mux-bot

mux-bot Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

New in this run: cleanup #3 — deduped the identical blockquote line-prefixing (> per line, joined by newlines) in buildBashMonitorWakePrompt into a module-level blockquoteLines(lines) helper. Behavior-preserving; validated by the existing buildBashMonitorWakePrompt output-format tests (21/21 pass).

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from d8d0ba5 to 78cd7b2 Compare July 9, 2026 20:38
@mux-bot

mux-bot Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from 78cd7b2 to a676f79 Compare July 10, 2026 00:30
@mux-bot

mux-bot Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

Added auto-cleanup #5: getCodexOauthContextLimit now reuses the already-resolved, non-null compatibilityModelId with the isCodexOauthAllowedModelId / isCodexOauthRequiredModelId variants instead of re-invoking isCodexOauthAllowedModel / isCodexOauthRequiredModel (which re-derive the same id and re-scan providersConfig). Behavior-preserving; targeted tests + make static-check (minus sandbox-only shfmt) pass.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from a676f79 to 32928e3 Compare July 10, 2026 09:08
@mux-bot

mux-bot Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

Added cleanup #6: extracted a module-private getAnthropicCacheCreateTokens(metadata) helper in usageHelpers.ts to dedupe two byte-identical Anthropic cache-create token reads inside accumulateProviderMetadata. Behavior-preserving; rebased onto latest main (checkpoint ec47caf).

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from 32928e3 to 8afce4c Compare July 10, 2026 16:47
@mux-bot

mux-bot Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from 8afce4c to 990576b Compare July 11, 2026 00:26
@mux-bot

mux-bot Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

Added cleanup #7: deduped the byte-identical QueueClearCallbacks projection in MessageQueue.getClearCallbacks and removeWorkspaceTurn into a private entryClearCallbacks(entry) helper (behavior-preserving). Rebased onto latest main and advanced the checkpoint to 956ac533e.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch 2 times, most recently from cd778d7 to 08734b9 Compare July 12, 2026 00:27
@mux-bot

mux-bot Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

This run adds one behavior-preserving cleanup (#8 in the branch list): dedupes the two identical openai-origin model checks in openaiExplicitPromptCachingAvailable (cacheStrategy.ts, introduced by #3712) into a module-private isOpenAIOriginModel(canonical) helper. The destructured origin/modelName locals were unused past their guard. Rebased onto origin/main (48722b9); make static-check passes (except fmt-shell-check, which needs shfmt unavailable in this env) and the cacheStrategy/providerOptions test suites pass (173).

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from 08734b9 to b42facd Compare July 13, 2026 12:53
@mux-bot

mux-bot Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch 2 times, most recently from ea234fd to 4186ae0 Compare July 15, 2026 16:35
@mux-bot

mux-bot Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from 4186ae0 to 5769a3c Compare July 15, 2026 16:39
@mux-bot

mux-bot Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot

mux-bot Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor Author

⚠️ Auto-fixup determined this CI failure is a flaky test, not caused by the cleanup commit — no code was pushed.

Failing job: Test / Unit (run 29433315697)

Failing test: WorkspaceService bash monitor wakes > leaves idle rejected monitor wakes pending without scheduling a retry loop

Diagnosis:

  • CI failure duration was 1006.01ms, which matches waitForCondition's default 1000ms timeout (src/node/services/testDispatchHelpers.ts) throwing Timed out after 1000ms waiting for condition. The test polls for an async sendMessage dispatch (microtasks + timers) that did not fire within the window under heavy CI parallelism (9773 tests / 679 files / ~405s).
  • The only cleanup change in the monitor-wake area (src/node/services/bashMonitorWakeStore.ts) is a pure refactor extracting a blockquoteLines helper used by buildBashMonitorWakePrompt (prompt-string building). It does not touch the dispatch/scheduling path this test measures. No other changed file is in this test's (heavily mocked) dispatch path.

Local reproduction:

  • Isolated: 5/5 passes, 33–183ms each.
  • Full file: bun test src/node/services/workspaceService.test.ts270 pass, 0 fail in ~2.0s.

Recommendation: re-run the Test / Unit job. If this test proves persistently flaky, consider raising its waitForCondition timeoutMs to de-flake under CI load.


Generated with mux • Model: anthropic:claude-opus-4-8 • Thinking: xhigh • Cost: $0.00

mux-bot Bot added 16 commits July 15, 2026 20:21
Extract the byte-identical consolidation/harvest sweep `recordUsage`
callbacks in MemoryConsolidationService into a shared
`makeSweepUsageRecorder` helper. Behavior-preserving: same sidecar
recording and analyticsIngest emit; only the workspaceId source and
analyticsSource literal differ per call site.

Auto-cleanup checkpoint: f7f0f02
Both fallback branches in prepareToolSearch inlined the identical
{ [TOOL_SEARCH_TOOL_NAME]: _removed, ...rest } destructure to drop the
built-in tool_search entry from the record. Extract a module-level
withoutToolSearch(tools) helper; output is byte-identical.
accumulateProviderMetadata inlined the same verbose (metadata.anthropic as { cacheCreationInputTokens?: number }).cacheCreationInputTokens ?? 0 cast twice. Extracted a module-private getAnthropicCacheCreateTokens(metadata) helper. Behavior-preserving; the displayUsage.ts site is intentionally left alone because its chain has an extra usage.inputTokenDetails.cacheWriteTokens fallback.
Both getThinkingPolicyForModel and hasExplicitThinkingPolicy inlined the
identical getExplicitThinkingPolicy(resolveModelForMetadata(model, providersConfig ?? null))
call after #3708 added alias resolution to each. Extract a private
getExplicitThinkingPolicyForModel helper; behavior-preserving.
Both eligibility gates in openaiExplicitPromptCachingAvailable inlined the
identical split(":", 2) + `origin !== "openai" || !modelName` check (once for
the request model, once for the resolved capability target). The destructured
origin/name locals were unused past their guard. Extracted into a module-private
isOpenAIOriginModel(canonical) helper. Behavior-preserving.
renameLegacyToolSearchCallPart and renameLegacyToolSearchResultPart were byte-identical except for their part type. Collapse them into a single generic renameLegacyToolSearchPart<T extends { toolName: string }> and drop the now-unused ToolCallPart/ToolResultPart imports. Behavior-preserving.
The CODEX_OAUTH_CONTEXT_WINDOW_OVERRIDES doc comment already explains that these caps are kept separate from model metadata so API-key requests retain the public window. #3724 rewrote the inline comment to restate the same point, so trim the duplicated sentence and keep only the tier-specific rationale. Comment-only; behavior-preserving.
Dedupe the repeated event.errorType member access and the duplicated
event.errorType != null guard introduced by #3729 into a single local
const. Pure behavior-preserving simplification; ErrorEvent.errorType is
a plain Zod-inferred data property with no side effects.
@mux-bot mux-bot Bot force-pushed the auto-cleanup branch from 5769a3c to cbefdbe Compare July 15, 2026 20:28
@mux-bot

mux-bot Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@mux-bot

mux-bot Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor Author

🤖 Auto-fixup diagnosis: flaky test, no code fix pushed.

CI run 29448420645 failed only in Test / Integration with a single failing test:

● Runtime integration tests › SSHRuntime sync does not import stale remote tracking refs
  › initWorkspace repairs a reusable snapshot whose base repo is missing objects

thrown: "Exceeded timeout of 120000 ms for a test."
  at tests/runtime/runtime.test.ts:1835

Why this is flaky and not caused by the cleanup commit:

  • It's a per-test timeout (120s exceeded), not an assertion failure. The full runtime.test.ts suite ran ~245s, so a slow SSH/git integration test simply overran its budget on this runner.
  • This PR touches no test files and none of the cleanup-touched files sit on the SSH initWorkspace / git-snapshot-repair code path. Touched files are unrelated refactors (helper extraction, local-variable hoisting, dedup) in AI/skills/tokens/schema/service modules.
  • The only taskService reference in runtimeFactory.ts (the module this test imports) is a comment, and the taskService change is a no-op errorType hoist in the stream-error finalization path — unrelated to runtime init.
  • All other jobs (Static Checks, Unit, E2E, Storybook, Windows, Builds) passed; sendMessage.errors self-recovered on retry.

No code changes are safe or warranted here. Recommend re-running the failed job; this should pass on retry.


Generated with mux • Model: anthropic:claude-opus-4-8 • Thinking: xhigh

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.

0 participants