The influence of the gut microbiota on long-term immune checkpoint inhibitor (ICI) efficacy and immune-related adverse events (irAEs) is poorly understood, as are the underlying mechanisms. We performed gut metagenome and metabolome sequencing of gut microbiotas from patients with lung cancer initially treated with anti-PD-1/PD-L1 therapy and explored the underlying mechanisms mediating long-term (median follow-up 1167 days) ICI responses and immune-related adverse events (irAEs). Results were validated in external, publicly-available datasets (Routy, Lee, and McCulloch cohorts). The ICI benefit group was enriched for propionate (P=0.01) and butyrate/isobutyrate (P=0.12) compared with the resistance group, which was validated in the McCulloch cohort (propionate P<0.001, butyrate/isobutyrate P=0.002). The acetyl-CoA pathway (P=0.02) in beneficial species mainly mediated butyrate production. Microbiota sequences from irAE patients aligned with antigenic epitopes found in autoimmune diseases. Microbiotas of responsive patients contained more lung cancer-related antigens (P=0.07), which was validated in the Routy cohort (P=0.02). Escherichia coli and SGB15342 of Faecalibacterium prausnitzii showed strain-level variations corresponding to clinical phenotypes. Metabolome validation reviewed more abundant acetic acid (P=0.03), propionic acid (P=0.09), and butyric acid (P=0.02) in the benefit group than the resistance group, and patients with higher acetic, propionic, and butyric acid levels had a longer progression-free survival and lower risk of tumor progression after adjusting for histopathological subtype and stage (P<0.05). Long-term ICI survivors have coevolved a compact microbial community with high butyrate production, and molecular mimicry of autoimmune and tumor antigens by microbiota contribute to outcomes. These results not only characterize the gut microbiotas of patients who benefit long term from ICIs but pave the way for "smart" fecal microbiota transplantation. Registered in the Chinese Clinical Trial Registry (ChiCTR2000032088). This work was supported by Beijing Natural Science Foundation (7232110), National High Level Hospital Clinical Research Funding (2022-PUMCH-A-072, 2023-PUMCH-C-054), CAMS Innovation Fund for Medical Sciences (CIFMS) (2022-I2M-C&T-B-010).