The normalizers extraction in #1168 introduced a circular module-load
chain that crashed the built CLI:
ccs.js -> errors -> services/logging -> log-config -> config-loader-facade
-> unified-config-loader -> loader/normalizers -> channels/official-channels-runtime
-> utils/claude-detector -> utils/shell-executor -> utils/websearch-manager
-> utils/websearch/hook-env -> utils/websearch/trace
-> services/logging (mid-load - createLogger undefined) -> CRASH
normalizers only needed three pure helpers from official-channels-runtime
(isOfficialChannelId, normalizeOfficialChannelIds, resolveLegacyDiscord
Selection) but pulled in the whole file's claude-detector / shell-
executor / websearch chain.
Fix: extract those three helpers + OFFICIAL_CHANNEL_IDS into a leaf
module src/channels/official-channels-ids.ts with no runtime deps.
Update normalizers.ts and config-getters.ts to import from the leaf.
official-channels-runtime.ts re-exports from the leaf for callers that
still want the bundled API.
Also revert the over-eager facade-import migration in
src/utils/config-manager.ts (it was importing from config-loader-facade
which re-exports from itself, creating a direct cycle).
Verified: dist/ccs.js boots cleanly (--version returns); test:all
1828/1828 pass; typecheck/lint/format clean.
Refs #1135
Issue #1161. Sweeps 127 files to import from
src/config/config-loader-facade.ts instead of unified-config-loader or
utils/config-manager directly.
WRITE callers (32 files): replaced raw saveUnifiedConfig /
mutateUnifiedConfig / updateUnifiedConfig calls with the facade's
cache-coherent wrappers saveConfig / mutateConfig / updateConfig. This
fixes a latent stale-cache window where direct writes through the
underlying loader bypassed the facade's memoization.
READ callers (95 files): mechanical import-path migration only —
function names unchanged because the facade re-exports them. No
behavior change.
Also updated:
- tests/unit/utils/browser/browser-setup.test.ts (DI interface rename)
- src/management/checks/image-analysis-check.ts (dynamic import rename)
- src/web-server/health-service.ts (dynamic require rename)
- src/ccs.ts (path prefix fix from sweep script)
After sweep: zero raw write callers remain outside src/config/. Direct
imports of config-manager remain only for symbols not in the facade
(getConfigPath, getCcsDirSource, etc). Behavior unchanged; full suite
passes 1824/1824.
Out of scope: switching loadOrCreateUnifiedConfig() callers to
getCachedConfig() — needs per-callsite cache-safety analysis. Tracked
as follow-up.
Refs #1161
Phases 4-6 of #1164. Final extractions and orchestrator cleanup:
- src/config/loader/defaults-merger.ts (323 LOC):
mergeWithDefaults — pure transform that fills defaults across browser,
websearch, dashboard auth, image analysis, logging, cursor, continuity,
official channels.
- src/config/loader/config-getters.ts (339 LOC):
getWebSearchConfig, getGlobalEnvConfig, getContinuityInheritanceMap,
getCliproxySafetyConfig, getThinkingConfig, getOfficialChannelsConfig,
isDashboardAuthEnabled, getDashboardAuthConfig, getBrowserConfig,
getImageAnalysisConfig, getLoggingConfig, getCursorConfig,
GeminiWebSearchInfo. Lazy require('../unified-config-loader') call-time
resolution preserves spy-based test compatibility while breaking the
config-getters -> orchestrator cycle.
- unified-config-loader.ts: rewritten as 268-LOC orchestrator. Hosts core
load/save/mutate logic + re-exports of all moved symbols for backwards
compat with codebase imports.
Forward-reference callbacks in io-locks.ts kept as-is — defaults-merger
and normalizers don't import from io-locks (no cycle), but simplifying
io-locks's internal callback API risks lock-semantics regression.
Deferred per KISS.
unified-config-loader.ts: 1508 -> 268 LOC (-1240, -82%). Behavior
unchanged; full suite passes 1824/1824.
Refs #1164
Phases 5+6 of #1165. Final big extraction: collapses the 6-branch
profileInfo.type switch in main() into a single dispatchProfile call.
- src/dispatcher/dispatcher-context.ts (40 LOC): ProfileDispatchContext type
- src/dispatcher/flows/cliproxy-flow.ts (211 LOC)
- src/dispatcher/flows/copilot-flow.ts (66 LOC)
- src/dispatcher/flows/cursor-flow.ts (54 LOC)
- src/dispatcher/flows/settings-flow.ts (400 LOC)
- src/dispatcher/flows/settings-image-analysis-prep.ts (126 LOC):
split out per plan to keep settings-flow control flow whole
- src/dispatcher/flows/account-flow.ts (63 LOC)
- src/dispatcher/flows/default-flow.ts (136 LOC)
- src/dispatcher/target-executor.ts (+38 LOC): dispatchProfile switch
settings-flow stays at 400 LOC — flow control (3 pre-flight blocks +
env construction + 2 dispatch paths) is maximally cohesive. Further
splitting would fragment dispatch logic per plan note.
process.exit parity preserved exactly (cliproxy non-claude path uses
process.exitCode=1; return; others use process.exit(1)).
ccs.ts: 1040 -> 170 LOC (-870). Full reduction across phases 1-6:
1775 -> 170 (-1605, -90%). main() body now ~100 LOC of awaited phase
calls. Behavior unchanged; full suite passes 1824/1824.
Refs #1165
Phase 4 of #1165. Extracts the largest remaining concern in main():
profile detection, target resolution, Claude CLI detection, adapter
lookup, compatibility preflight, binary detection, droid prune, and
per-target arg normalization.
- src/dispatcher/profile-resolver.ts (358 LOC):
resolveProfileAndTarget + ProfileResolutionContext / ResolvedProfile
types. Includes droid + codex per-target arg normalization (cohesive
with profile resolution; splitting would create incomplete extraction).
- 7 unit tests covering default, gemini, codex, unknown profile, droid,
and compatibility preflight runs.
Compatibility preflight duplication between this phase and the settings
flow (Phase E) is preserved exactly per plan risk note 5 — do not dedupe
in this PR. Module is 358 LOC (over 300 ideal) — kept whole because the
profile resolution + per-target normalization form a single dependency
chain.
ccs.ts: 1262 -> 1040 LOC (-222). Behavior unchanged; full suite passes
1824/1824.
Refs #1165
Phase 07 of #1162. Splits tool-sanitization + codex-reasoning proxy spawn
out of the orchestrator:
- src/cliproxy/executor/proxy-chain-builder.ts (185 LOC):
buildProxyChain + ProxyChainContext / ProxyChainResult types.
DI escape hatch (_ToolSanitizationProxy / _CodexReasoningProxy) for
testability without refactoring the proxy classes (Bun module cache
blocks mock.module of already-loaded modules).
- 9 unit tests covering codex-only, tool-san only, both-together,
spawn failure swallowing, env propagation.
index.ts: 716 -> 665 LOC (-51). HTTPS tunnel kept inline because
tunnelPort is needed by image-analysis resolution before first-pass
buildClaudeEnvironment — folding it in would also require moving image
analysis. Two-pass buildClaudeEnvironment dance preserved exactly.
Behavior unchanged; full suite passes 1824/1824.
Refs #1162
Phase 06 of #1162. Splits the largest remaining concern out of the
orchestrator into a focused module:
- src/cliproxy/executor/auth-coordinator.ts (397 LOC):
handleLogout, handleImport, resolveSkipLocalAuth, runAntigravityGate,
ensureProviderAuthentication, runPreflightQuotaCheck,
runAccountSafetyGuards, ensureModelConfiguration,
ensureProviderSettingsFile. Preserves load-bearing ordering of
antigravity gate -> auth -> token refresh -> quota check.
- 36 unit tests covering --auth/--logout/--import early exit,
antigravity gate refusal/acceptance, OAuth trigger paths, composite
providers, remote-proxy skipLocalAuth.
index.ts: 895 -> 716 LOC (-179). Behavior unchanged; full suite passes
1824/1824. Module is 397 LOC (over the <200 ideal) — kept whole because
the auth ordering contract should not be split across files.
Refs #1162
Phases 04+05 of #1162. Splits two more concerns out of the orchestrator:
- src/cliproxy/executor/browser-launch-setup.ts (118 LOC):
resolveBrowserLaunchFlags + resolveBrowserRuntime. Encapsulates browser
flag resolution, attach config, blocked-override warning, and runtime
setup including MCP sync.
- src/cliproxy/executor/account-resolution.ts (197 LOC):
resolveRuntimeQuotaMonitorProviders, resolveAccounts (--accounts /
--use / --nickname / OAuth ban-risk warn / default touch),
applyAccountSafetyGuards, touchDefaultAccount.
- New tests: 184 + 430 LOC covering both modules.
index.ts: 1045 -> 895 LOC (-150). resolveRuntimeQuotaMonitorProviders
re-exported from index.ts for __testExports backwards compat. Behavior
unchanged; full suite passes 1824/1824.
Refs #1162
Phase 03 of #1162. Splits proxy + binary resolution out of the orchestrator
into a focused module:
- src/cliproxy/executor/proxy-resolver.ts (196 LOC):
ResolvedProxy + ResolveExecutorProxyContext interfaces, resolveExecutorProxy
function. Encapsulates proxy config resolution, port mutation, remote
reachability check, fallback prompt, local backend selection, and
binary acquisition.
- src/cliproxy/executor/__tests__/proxy-resolver.test.ts: 10 unit tests
covering local/remote/fallback paths.
index.ts: 1168 -> 1045 LOC (-123). Removes 9 now-unused imports. Browser
flag handling intentionally left in index.ts for Phase 04. Behavior
unchanged; full suite passes 1824/1824.
Refs #1162
Phases 01+02 of #1162. Splits executor flag parsing/validation out of the
1428-LOC orchestrator into a focused module:
New files:
- src/cliproxy/executor/arg-parser.ts (~500 LOC):
readOptionValue, hasGitLabTokenLoginFlag, getGitLabTokenLoginFlagName,
CCS_FLAGS + filterCcsFlags, ParsedExecutorFlags + parseExecutorFlags,
validateFlagCombinations (process.exit semantics preserved for parity).
- src/cliproxy/executor/__tests__/arg-parser.test.ts: 45 unit tests.
- src/cliproxy/executor/__tests__/index-characterization.test.ts:
TDD baseline (16 pass + 7 skipped scenarios at the spawn/dynamic-import
boundary; mock simplification deferred to a follow-up phase).
index.ts: 1428 -> 1175 LOC (-253). Re-exports preserved at module bottom
for backwards compatibility. Behavior unchanged; full test suite passes
(1824/1824).
Refs #1162
Adding a separate STAGE column squeezed MESSAGE to 0px at the
default 22/52/26 panel split — fixed columns + gaps totalled more
than the list panel's available width.
Render the stage chip inline at the start of the MESSAGE column when
present, restoring the original 7-column grid. The bot's earlier
"extra cell mismatch" complaint is still satisfied because there's
no longer a row-only cell missing from the header.
Also tighten three fixed columns to give MESSAGE more breathing room
even on narrower saved panel layouts:
- Module 140 -> 120
- Latency 72 -> 64
- Request 112 -> 100
PR-Agent flagged that the leaf coalesceKey omitted `stage`, so two
adjacent no-requestId logs differing only by stage (e.g. one logging
`route` and the next `dispatch`) would merge into a single `×2`
row, hiding a distinct entry.
Add `stage` to the coalesce tuple. New unit test asserts that two
leaves identical except for stage stay as separate rows.
Refs #1138, #1151
PR-Agent flagged that the trace-child coalesce was hiding legitimate
repeated stage emissions: a request that retries an upstream call or
emits the same stage twice for any reason would show only the first
occurrence behind a `×N` badge, with subsequent attempts no longer
selectable or inspectable.
The original noise problem motivating intra-trace coalesce was the
149-stage `web-server:http` self-polling trace, but that's already
hidden by default via the `hideDashboardInternals` filter. Users who
opt in to see internals are deliberately debugging the dashboard and
SHOULD see all 149 stages — collapsing them defeats the opt-in.
Drop `coalesceChildren` entirely. Trace children render uncoalesced
so retries, duplicated stages, and multi-attempt traces stay
individually inspectable. Standalone-leaf coalesce stays — that's
the actual user-facing dedup the PR was about.
Tests: drop the 7 `coalesceChildren` cases; keep 16 covering
`deriveStageHint` and `deriveTraceGroups`.
Refs #1138, #1151
PR-Agent flagged that trace child rows rendered an extra stage-hint
cell while the header grid template only had 7 columns. Result: every
expanded child shifted module/message/latency/request rightward, and
the stage chip overlapped its neighbour in the trace timeline.
Add a dedicated 72px "Stage" column to the header grid template and
to every row variant. Standalone leaves and trace heads render an
empty span at the same width; trace children with stage hints render
the chip in that slot. Column edges now match across all row types.
Refs #1138, #1151
The first click on a trace's chevron did nothing visible when the
trace's child was the currently-selected entry. Root cause: `toggle`
only checked the `expanded` set; auto-expand kept re-injecting the
requestId so the row stayed open even after the user added it to
`expanded` (and oscillating subsequent clicks).
Replace the single `expanded` set with a tristate driven by two
sets — `userExpanded` (explicitly opened) and `userCollapsed`
(explicitly closed). Auto-expand only fires when the id is in
neither, so a click on an auto-expanded chevron now writes the
collapse intent to `userCollapsed` and the row collapses on the
first click.
Refs #1138, #1151
getCachedConfig() now checks config file mtime on each call.
If external code writes via unified-config-loader directly,
the facade detects the file change and re-reads from disk
automatically. Resolves PR-Agent "Stale Cache" finding.
PR-Agent flagged that the previous derive-trace-groups split entries
into trace and leaf buckets *before* coalescing leaves. That meant two
identical no-requestId entries separated by other rows in the real
stream would still merge into a single `×N` row, hiding signal.
Walk `entries` in input order with single-pass coalescing: a leaf
only extends the previous leaf when no other entry (trace child or
otherwise) appeared between them. Trace children still gather across
interleaving since they're identified by `requestId`. Group children
get sorted ts-ascending for trace-timeline display, with the group's
positional ts pinned to the oldest child for the reverse-chrono
display sort.
Refs #1138, #1151
PR-Agent flagged that `React.MouseEvent` referenced an unimported
`React` namespace; in stricter TypeScript builds this would fail
typecheck. Import the type alias from `react` directly.
Refs #1138, #1151