Repository navigation
[refactor] Semantic Function Clustering AnalysisΒ #12985
Description
π§ Semantic Function Clustering Analysis
Analysis of repository: github/gh-aw-mcpg β internal/ directory (~180 non-test .go files)
Executive Summary
No open [refactor]-prefixed issues were found to close before starting this analysis (existing [duplicate-code]-prefixed issues belong to a separate workflow and were left untouched). I scanned every non-test .go file under internal/, extracted ~1,400 top-level function/method declarations, clustered them by name/purpose, and cross-referenced same-named functions across files/packages to look for outliers and duplication. The codebase is generally well organized (small, single-purpose files, consistent validation_*.go / flags_*.go / guard_*.go naming families). I found a handful of near-duplicate implementations worth consolidating, and no clear "function in the wrong file" outliers of significant size β most validate*/Validate* occurrences outside internal/config are legitimately package-local (auth, delegation, launcher, enclavegithub each validate their own domain types) rather than misplaced config validation.
Function Inventory (highlights)
- internal/config/: 18 files, ~90 functions, split cleanly into
validation_{env,errors,gateway,rules,schema,server,tracing}.go,config_{core,feature,stdin,tracing}.go,expand.go,guard_policy*.go. Well organized β - internal/guard/: 11 files implementing the
Guardinterface (NoopGuard,WasmGuard,WriteSinkGuard) β each guard repeats the same method set (LabelAgent,LabelResource,LabelResponse,NewSessionGuard), which is expected interface-implementation duplication, not a smell. - internal/server/ + internal/proxy/: delegation control-plane wiring duplicated (
ControlHandler,handleDelegationControl) β flagged below. - internal/tty/:
tty.go/tty_stub.goboth defineIsStderrTerminalβ intentional Go build-tag pattern (!tty_stubvstty_stub), not a duplicate. - internal/delegation/identity.go:
toRequestdefined twice in the same file on different receivers (delegationBindingand*Identity) with near-identical field-copy bodies.
Identified Issues
1. Duplicate Delegation Control-Plane Wiring (proxy vs server)
- Files:
internal/proxy/delegation.go(lines 40β65) andinternal/server/delegation.go(lines 173β189) - Functions:
ControlHandler()andhandleDelegationControl(w, r)are defined nearly identically on*proxy.Serverand*server.UnifiedServer. Both build adelegation.ControlDeps{Store, Capability, StatePath}from local fields and calldelegation.HandleControl(...)with a logger'sPrintf, gated by anhttp.NotFoundprefix check ondelegation.ControlPathPrefix. - Similarity: ~90% structurally identical; only field access paths differ (
h.server.delegation.*vsus.delegation.*). - Recommendation: Extract a small shared helper in
internal/delegation(e.g.delegation.NewControlHandler(deps ControlDeps, logf func(string, ...any)) http.Handlerplus aControlDepsProviderinterface with aControlDeps() ControlDepsmethod) so bothproxy.Serverandserver.UnifiedServercan construct their control handler via one shared call, eliminating the duplicatedhttp.NotFound/prefix-check/dispatch logic in both packages. - Estimated Impact: ~25 duplicated lines removed; single source of truth for the control-plane guard logic.
2. Duplicate Struct-to-Request Conversion (toRequest)
- File:
internal/delegation/identity.go - Functions:
(b delegationBinding) toRequest(...)(line 70) and(id *Identity) toRequest()(line 161) - Issue: Both copy the same 8 fields (
RunID,EnclaveBackend,EnclaveEntryID,InvocationID,Repository,ToolPolicy,SchemaHash,AdmittedDefaultBranchSHA) into aCreateOrConfirmRequest. SinceIdentityalready embeds/derives adelegationBinding-shaped value,(*Identity).toRequest()could likely delegate todelegationBinding.toRequest(...)instead of re-listing every field. - Recommendation: Have
Identity.toRequest()build/reuse adelegationBindingand callbinding.toRequest(...), removing one full field-copy block. - Estimated Impact: Minor, but removes a silent-drift risk (a future field added to one struct but not the other).
3. Scattered Format* / formatting helpers (acceptable, monitor)
internal/util/format.go,internal/config/error_format.go,internal/logger/rpc_format.go,internal/logger/slog_adapter.go, andinternal/difc/violations.goeach define their ownformat*helpers with no shared implementation. Each serves a distinct domain (session IDs, config errors, RPC message text, slog value stringification, DIFC violation messages), so this is not flagged as a hard duplicate β but if a generic "truncate + label" pattern keeps recurring, consider consolidating trivial string-formatting helpers intointernal/util/format.go, which already exists as the shared utility home.
4. validate*/Validate* outside internal/config β reviewed, not outliers
Occurrences in internal/sys/docker.go, internal/proxy/tls.go, internal/util/collections.go (generic ValidateUnique[T]), internal/server/{guard_visibility,session,tool_registry,guard_init}.go, internal/auth/header.go, internal/delegation/{recovery,store,envelope}.go, internal/launcher/mount_policy.go, and internal/enclavegithub/{policy,capability}.go were reviewed individually. Each validates a type/concept owned by its own package (container IDs, TLS DNS names, session extraction, agent-policy tools, delegation envelopes/state, mount specs, enclave policy/claims) rather than generic config validation β correctly located, no move recommended.
Refactoring Recommendations
Priority 1
- Consolidate delegation control-plane handler wiring (
internal/proxy/delegation.go+internal/server/delegation.go) into a sharedinternal/delegationhelper. Estimated effort: 1β2 hours. Benefit: removes ~25 duplicated lines and a maintenance hazard where the two copies could drift (e.g., one gaining a security check the other misses).
Priority 2
- Deduplicate
toRequestconversions ininternal/delegation/identity.goby havingIdentity.toRequest()delegate todelegationBinding.toRequest(). Estimated effort: 30 minutes. Benefit: single source of truth for the request field mapping.
Priority 3 (monitor only, no action needed now)
- Keep an eye on scattered
format*helpers β no action recommended today since each is domain-specific and small.
Analysis Metadata
- Total Go files analyzed: ~180 (non-test, under
internal/) - Total functions/methods cataloged: ~1,400
- Duplicate/near-duplicate clusters flagged: 2 (delegation control-plane wiring,
toRequestconversion) - False positives ruled out: guard interface implementations (
NoopGuard/WasmGuard/WriteSinkGuard), tty build-tag variants (tty.go/tty_stub.go),MatchRoute(different packages/signatures),validate*functions outsideinternal/config(correctly domain-scoped) - Detection method: static grep-based function inventory + cross-file name/signature comparison (Serena MCP tools were not available in this environment's toolset; GitHub MCP + shell-based static analysis used instead)
- Analysis date: 2026-09-11
Generated by Semantic Function Refactoring Β· copilot Β· auto Β· 50.4 AIC Β· β 13.2K Β· β·
Activity