text:
Country Code Transformations
Background and Motivation:
IOC Country Codes are three letter abbreviations that are commonly used when broadcasting the Olympic Games. The last two letters of some codes overlap with the first two letters of other codes (RUS -> USA, JPN -> PNG), etc. Clearly, you can transform the first country code into the second by removing the first letter, and adding a new letter at the end. Sometimes, you can chain these transformations into a longer path (RUS -> USA -> SAM).
I want to find determine whether a path exists between 2 given country codes (using a provided list like the IOC list or the FIFA list) in order to impress party guests, and in the event that multiple paths exist, I'd like to output the longest one. To keep the output small enough to sneak into a commercial break, paths are compressed by not repeating common substrings between adjacent country codes: RUS -> USA -> SAM would be written as RUSAMfor example.
If multiple equal length paths are possible, you can select any result (previously asked for a deterministic tiebreaking rule that "I could explain to a partygoer." I would still appreciate answers that include this, but it's probably not a good objective rule that constrains whether an answer is correct.)
The Technical Challenge
Inputs:

initial 3 letter country code
terminal 3 letter country code
set of valid 3 letter country codes

Outputs:
Determine whether a string exists such that:

the first three letters are identical to the initial 3 letter country code
The last three letters are identical to the terminal 3 letter country code
each 3-letter substring corresponds to a valid country code from the input set
the same country code cannot appear twice in the string (with the exception that the first 3 characters and the last 3 characters can be the same)

If one such string exists, print that string as the output. If multiple such strings exist, print the longest such string. If no such string exists, any of the following are acceptable:

no output
falsey output
error

Other ways of indicating that no such path exists are also allowed as long as they can't be confused for a valid path.
Valid Assumptions:
*The initial 3 letter country code and the terminal 3 letter country code are both contained in the provided set of valid 3 letter country codes.
Invalid Assumptions:
*The input set cannot be assumed to be ordered for purposes of producing a deterministic output.
*The initial 3 letter country code cannot be assumed to be different from the terminal country code (cyclic requests are allowed)
Extra Style Points (Not Necessary for Submission to be Valid):
If your answer includes a description of a deterministic tie-breaking rule you are using to determine which string to output when multiple identical length strings exist that meet all the above criteria, then you'll make this internet stranger very happy. Preferably something easy enough to explain to a random Olympics viewer, which is too fuzzy to be a good requirement for a valid submission.
Scoring:
This is code golf, so the shortest answer (in bytes) wins. Standard Loopholes apply.
Test Cases
Input 1: "AAA", "ZZZ", ["AAA", "AAZ", "AZZ", "ZZZ"]
Output 1: "AAAZZZ" (Find valid path if it exists)
Input 2: "AAA", "ZZZ", ["AAA", "AAZ", "AZZ", "ZZZ", "AAB", "ABB", "BBB", "BBZ", "BZZ", "ZZZ"]
Output 2: "AAABBBZZZ" (Find longest path if short and long paths both exist)
Input 3: "AAA", "ZZZ", ["AAA", "ZZZ"]
Output 3: Crash, falsey message, or no output (just don't output "AAAZZZ" or something that could be confused for a path)
Input 4: "AAA", "ZZZ", ["AAA", "AAB", "ABZ", "BZZ", "AAY", "AYZ", "YZZ", "ZZZ"],
Output 4: "AAABZZZ" OR "AAAYZZZ", but you must explain what rule decided which one to output (consistent behavior that follows your chosen rule)
Input 5: "AAA", "AAA", ["AAA", "ABA", "AAB", "BAA"],
Output 5: "AAABAAA" (Test case where initial code == terminal code, but other codes should be included in result)
Input 6: "AAA", "AAA", ["AAA", "ABA"],
Output 6: "AAA" ("AAABAAA" is not valid because "AAB" and "BAA" are 3 letter substrings contained in the answer which are not part of the valid set of country codes)
Input 7: "ISL", "ERI",
["AFG", "AHO", "AIA", "ALB", "ALG", "AND", "ANG", "ANT", "ARG", "ARM", "ARU", "ASA", "AUS", "AUT", "AZE", "BAH", "BAN", "BAR", "BDI", "BEL", "BEN", "BER", "BHU", "BIH", "BIZ", "BLR", "BOL", "BOT", "BRA", "BRN", "BRU", "BUL", "BUR", "CAF", "CAM", "CAN", "CAY", "CGO", "CHA", "CHI", "CHN", "CIV", "CMR", "COD", "COK", "COL", "COM", "CPV", "CRC", "CRO", "CUB", "CYP", "CZE", "DEN", "DJI", "DMA", "DOM", "ECU", "EGY", "ERI", "ESA", "ESP", "EST", "ETH", "FAR", "FGU", "FIJ", "FIN", "FLK", "FPO", "FRA", "FSM", "GAB", "GAM", "GBR", "GBS", "GEO", "GEQ", "GER", "GHA", "GIB", "GRE", "GRL", "GRN", "GUA", "GUD", "GUI", "GUM", "GUY", "HAI", "HEL", "HKG", "HON", "HUN", "INA", "IND", "IRI", "IRL", "IRQ", "ISL", "ISR", "ISV", "ITA", "IVB", "JAM", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KIR", "KOR", "KSA", "KUW", "LAO", "LAT", "LBA", "LBR", "LCA", "LES", "LIB", "LIE", "LTU", "LUX", "MAC", "MAD", "MAR", "MAS", "MAW", "MAY", "MDA", "MDV", "MEX", "MGL", "MGO", "MKD", "MLI", "MLT", "MNT", "MON", "MOZ", "MRI", "MRT", "MSH", "MTN", "MYA", "NAM", "NCA", "NCD", "NED", "NEP", "NFI", "NGR", "NIG", "NIU", "NMA", "NOR", "NRU", "NZL", "OMA", "PAK", "PAN", "PAR", "PER", "PHI", "PLE", "PLW", "PNG", "POL", "POR", "PRK", "PUR", "QAT", "REU", "ROU", "RSA", "RUS", "RWA", "SAM", "SEN", "SEY", "SIN", "SKN", "SLE", "SLO", "SMR", "SOL", "SOM", "SPM", "SRB", "SRI", "STP", "SUD", "SUI", "SUR", "SVK", "SWE", "SWZ", "SYR", "TAN", "TGA", "THA", "TJK", "TKM", "TKS", "TLS", "TOG", "TPE", "TTO", "TUN", "TUR", "TUV", "UAE", "UGA", "UKR", "URU", "USA", "UZB", "VAN", "VEN", "VIE", "VIN", "WAF", "YEM", "ZAM", "ZIM"]

Output 7: ISLESTPERI (real world test case: IOC codes ISL -> SLE -> LES -> EST -> STP -> TPE -> PER -> ERI corresponding to Iceland -> Sierra Leone -> Lesotho -> Estonia -> Sao Tome and Principe -> Republic of China -> Peru -> Eritrea)
Input 8: USA, USA,
["ABW", "AFG", "AGO", "AIA", "ALA", "ALB", "AND", "ARE", "ARG", "ARM", "ASM", "ATA", "ATF", "ATG", "AUS", "AUT", "AZE", "BDI", "BEL", "BEN", "BES", "BFA", "BGD", "BGR", "BHR", "BHS", "BIH", "BLM", "BLR", "BLZ", "BMU", "BOL", "BRA", "BRB", "BRN", "BTN", "BVT", "BWA", "CAF", "CAN", "CCK", "CHE", "CHL", "CHN", "CIV", "CMR", "COD", "COG", "COK", "COL", "COM", "CPV", "CRI", "CUB", "CUW", "CXR", "CYM", "CYP", "CZE", "DEU", "DJI", "DMA", "DNK", "DOM", "DZA", "ECU", "EGY", "ERI", "ESH", "ESP", "EST", "ETH", "FIN", "FJI", "FLK", "FRA", "FRO", "FSM", "GAB", "GBR", "GEO", "GGY", "GHA", "GIB", "GIN", "GLP", "GMB", "GNB", "GNQ", "GRC", "GRD", "GRL", "GTM", "GUF", "GUM", "GUY", "HKG", "HMD", "HND", "HRV", "HTI", "HUN", "IDN", "IMN", "IND", "IOT", "IRL", "IRN", "IRQ", "ISL", "ISR", "ITA", "JAM", "JEY", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KHM", "KIR", "KNA", "KOR", "KWT", "LAO", "LBN", "LBR", "LBY", "LCA", "LIE", "LKA", "LSO", "LTU", "LUX", "LVA", "MAC", "MAF", "MAR", "MCO", "MDA", "MDG", "MDV", "MEX", "MHL", "MKD", "MLI", "MLT", "MMR", "MNE", "MNG", "MNP", "MOZ", "MRT", "MSR", "MTQ", "MUS", "MWI", "MYS", "MYT", "NAM", "NCL", "NER", "NFK", "NGA", "NIC", "NIU", "NLD", "NOR", "NPL", "NRU", "NZL", "OMN", "PAK", "PAN", "PCN", "PER", "PHL", "PLW", "PNG", "POL", "PRI", "PRK", "PRT", "PRY", "PSE", "PYF", "QAT", "REU", "ROU", "RUS", "RWA", "SAU", "SDN", "SEN", "SGP", "SGS", "SHN", "SJM", "SLB", "SLE", "SLV", "SMR", "SOM", "SPM", "SRB", "SSD", "STP", "SUR", "SVK", "SVN", "SWE", "SWZ", "SXM", "SYC", "SYR", "TCA", "TCD", "TGO", "THA", "TJK", "TKL", "TKM", "TLS", "TON", "TTO", "TUN", "TUR", "TUV", "TWN", "TZA", "UGA", "UKR", "UMI", "URY", "USA", "UZB", "VAT", "VCT", "VEN", "VGB", "VIR", "VNM", "VUT", "WLF", "WSM", "YEM", "ZAF", "ZMB", "ZWE"]

Output 8: "USAUSA" (real world test case: ISO3166-Alpha-3 codes representing the path USA -> SAU -> AUS -> USA corresponding to United States -> Saudi Arabia -> Australia -> United States)
Data:
All country codes for the real world examples was taken from https://datahub.io/core/country-codes#data if you want to play with it more. The paths were a lot shorter and less interesting than I thought they'd be when I started this question (I guess the country codes don't populate the space of 3 letter strings densely enough), but someone else may find something interesting to do with them.
Reference Code:
In case you prefer code you can play with over written test cases (or simply want to play with various paths but don't want to solve the challenge), here's some reference (ungolfed) code that solves all test cases quickly.
def pathfinder_helper(initial_code, terminal_code, valid_codes):
    if initial_code != terminal_code:
         if initial_code[1:] == terminal_code[:-1]:
            return [initial_code, terminal_code]

    if not valid_codes:
        if initial_code == terminal_code:
            return [initial_code]
        return None

    best_path = None
    for intermediate_code in valid_codes:
        # Pure speed optimization, can be left out and be "correct" but will be super slow on cases 7 and 8
        if initial_code[1:] != intermediate_code[:-1]:
            continue

        initial_intermediate_path = pathfinder_helper(initial_code, intermediate_code, valid_codes - {intermediate_code})
        intermediate_terminal_path = pathfinder_helper(intermediate_code, terminal_code, valid_codes - {intermediate_code})

        if initial_intermediate_path and intermediate_terminal_path:
            # Longer paths preferred
            if (best_path is None) or len(initial_intermediate_path + intermediate_terminal_path[1:]) >= len(best_path):
                if best_path and len(initial_intermediate_path + intermediate_terminal_path[1:]) == len(best_path):
                    # If lengths equal, use sort order (lexicographic)
                    if initial_intermediate_path + intermediate_terminal_path[1:] < best_path:
                        best_path = initial_intermediate_path + intermediate_terminal_path[1:]
                else:
                    best_path = initial_intermediate_path + intermediate_terminal_path[1:]
    return best_path

def pathfinder(initial_code, terminal_code, valid_codes):
    path = pathfinder_helper(initial_code, terminal_code, valid_codes - {initial_code, terminal_code})
    if path:
        return ''.join([path[0]] + [code[-1] for code in path[1:]])

print("Case 0:", pathfinder("AAA", "AAA", {"AAA"}))
print("Case 1:", pathfinder("AAA", "ZZZ", {"AAA", "AAZ", "AZZ", "ZZZ"}))
print("Case 2:", pathfinder("AAA", "ZZZ", {"AAA", "AAZ", "AZZ", "ZZZ", "AAB", "ABB", "BBB", "BBZ", "BZZ", "ZZZ"}))
print("Case 3:", pathfinder("AAA", "ZZZ", {"AAA", "ZZZ"}))
print("Case 4:", pathfinder("AAA", "ZZZ", {"AAA", "AAB", "ABZ", "BZZ", "AAY", "AYZ", "YZZ", "ZZZ"}))
print("Case 5:", pathfinder("AAA", "AAA", {"AAA", "ABA", "AAB", "BAA"}))
print("Case 6:", pathfinder("AAA", "AAA", {"AAA", "ABA"}))
print("Case 7:", pathfinder("ISL", "ERI", {"AFG", "AHO", "AIA", "ALB", "ALG", "AND", "ANG", "ANT", "ARG", "ARM", "ARU", "ASA", "AUS", "AUT", "AZE", "BAH", "BAN", "BAR", "BDI", "BEL", "BEN", "BER", "BHU", "BIH", "BIZ", "BLR", "BOL", "BOT", "BRA", "BRN", "BRU", "BUL", "BUR", "CAF", "CAM", "CAN", "CAY", "CGO", "CHA", "CHI", "CHN", "CIV", "CMR", "COD", "COK", "COL", "COM", "CPV", "CRC", "CRO", "CUB", "CYP", "CZE", "DEN", "DJI", "DMA", "DOM", "ECU", "EGY", "ERI", "ESA", "ESP", "EST", "ETH", "FAR", "FGU", "FIJ", "FIN", "FLK", "FPO", "FRA", "FSM", "GAB", "GAM", "GBR", "GBS", "GEO", "GEQ", "GER", "GHA", "GIB", "GRE", "GRL", "GRN", "GUA", "GUD", "GUI", "GUM", "GUY", "HAI", "HEL", "HKG", "HON", "HUN", "INA", "IND", "IRI", "IRL", "IRQ", "ISL", "ISR", "ISV", "ITA", "IVB", "JAM", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KIR", "KOR", "KSA", "KUW", "LAO", "LAT", "LBA", "LBR", "LCA", "LES", "LIB", "LIE", "LTU", "LUX", "MAC", "MAD", "MAR", "MAS", "MAW", "MAY", "MDA", "MDV", "MEX", "MGL", "MGO", "MKD", "MLI", "MLT", "MNT", "MON", "MOZ", "MRI", "MRT", "MSH", "MTN", "MYA", "NAM", "NCA", "NCD", "NED", "NEP", "NFI", "NGR", "NIG", "NIU", "NMA", "NOR", "NRU", "NZL", "OMA", "PAK", "PAN", "PAR", "PER", "PHI", "PLE", "PLW", "PNG", "POL", "POR", "PRK", "PUR", "QAT", "REU", "ROU", "RSA", "RUS", "RWA", "SAM", "SEN", "SEY", "SIN", "SKN", "SLE", "SLO", "SMR", "SOL", "SOM", "SPM", "SRB", "SRI", "STP", "SUD", "SUI", "SUR", "SVK", "SWE", "SWZ", "SYR", "TAN", "TGA", "THA", "TJK", "TKM", "TKS", "TLS", "TOG", "TPE", "TTO", "TUN", "TUR", "TUV", "UAE", "UGA", "UKR", "URU", "USA", "UZB", "VAN", "VEN", "VIE", "VIN", "WAF", "YEM", "ZAM", "ZIM"}))
print("Case 8:", pathfinder("USA", "USA", {"ABW", "AFG", "AGO", "AIA", "ALA", "ALB", "AND", "ARE", "ARG", "ARM", "ASM", "ATA", "ATF", "ATG", "AUS", "AUT", "AZE", "BDI", "BEL", "BEN", "BES", "BFA", "BGD", "BGR", "BHR", "BHS", "BIH", "BLM", "BLR", "BLZ", "BMU", "BOL", "BRA", "BRB", "BRN", "BTN", "BVT", "BWA", "CAF", "CAN", "CCK", "CHE", "CHL", "CHN", "CIV", "CMR", "COD", "COG", "COK", "COL", "COM", "CPV", "CRI", "CUB", "CUW", "CXR", "CYM", "CYP", "CZE", "DEU", "DJI", "DMA", "DNK", "DOM", "DZA", "ECU", "EGY", "ERI", "ESH", "ESP", "EST", "ETH", "FIN", "FJI", "FLK", "FRA", "FRO", "FSM", "GAB", "GBR", "GEO", "GGY", "GHA", "GIB", "GIN", "GLP", "GMB", "GNB", "GNQ", "GRC", "GRD", "GRL", "GTM", "GUF", "GUM", "GUY", "HKG", "HMD", "HND", "HRV", "HTI", "HUN", "IDN", "IMN", "IND", "IOT", "IRL", "IRN", "IRQ", "ISL", "ISR", "ITA", "JAM", "JEY", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KHM", "KIR", "KNA", "KOR", "KWT", "LAO", "LBN", "LBR", "LBY", "LCA", "LIE", "LKA", "LSO", "LTU", "LUX", "LVA", "MAC", "MAF", "MAR", "MCO", "MDA", "MDG", "MDV", "MEX", "MHL", "MKD", "MLI", "MLT", "MMR", "MNE", "MNG", "MNP", "MOZ", "MRT", "MSR", "MTQ", "MUS", "MWI", "MYS", "MYT", "NAM", "NCL", "NER", "NFK", "NGA", "NIC", "NIU", "NLD", "NOR", "NPL", "NRU", "NZL", "OMN", "PAK", "PAN", "PCN", "PER", "PHL", "PLW", "PNG", "POL", "PRI", "PRK", "PRT", "PRY", "PSE", "PYF", "QAT", "REU", "ROU", "RUS", "RWA", "SAU", "SDN", "SEN", "SGP", "SGS", "SHN", "SJM", "SLB", "SLE", "SLV", "SMR", "SOM", "SPM", "SRB", "SSD", "STP", "SUR", "SVK", "SVN", "SWE", "SWZ", "SXM", "SYC", "SYR", "TCA", "TCD", "TGO", "THA", "TJK", "TKL", "TKM", "TLS", "TON", "TTO", "TUN", "TUR", "TUV", "TWN", "TZA", "UGA", "UKR", "UMI", "URY", "USA", "UZB", "VAT", "VCT", "VEN", "VGB", "VIR", "VNM", "VUT", "WLF", "WSM", "YEM", "ZAF", "ZMB", "ZWE"}))

welcome to PPCG! this is a nice idea for a challenge, and well-specified for a first one. If you have doubts about a challenge (or even if you don't), you can post it in the sandbox to get feedback so it doesn't get downvoted into oblivion or closed. I hope you enjoy your time on the site!

Country codes, take me home, to the place I belong

@Giuseppe, thanks for the feedback. The only thing I wasn't sure about was specifying the output format as a string which is constructed in a way I can't figure out how to express clearly (although hopefully the test cases make it clear). Allowing output directly as [RUS, USA, SAM] might be better, but the current version actually matches the game as my family plays it (although we do go for shortest, not longest). Do you feel that I should make output more flexible or do you think its ok as it is?

Nice challenge but 2 pointers: Your introduction is too long-winded and, largely, irrelevant to the challenge - please consider editing it down. Input validation generally doesn't go down well; I'd suggest guaranteeing that there will always be a valid path. Welcome to the site :)

@Shaggy, I cut down on the intro significantly. I hope that improves the answer. I did look at this before writing the question. It feels weird to me to consider countries for which no paths exist as "invalid input", determining whether a path exists is a deliberate part of the problem. I will try rephrasing to make this clear.

@Abigail, "cyclic requests" was meant to clarify that the initial and terminal codes can be the same. "cyclic paths" (anywhere except the starting and final codes) are not valid answers because they would violate the rule "The same country code cannot appear twice in the string (with the exception the first 3 characters and last 3 characets can be the same)". This is because longest path from USA->USA is an interesting question we want to be able to answer, however as you said if cycles were allowed elsewhere then there is no longest path, you could always make a longer one.

As regards "deterministic": in Python, [c for c in set(["A", "B", "C"])]is deterministic in the sense that it always results in the same list (in a fixed order); but I can't easily tell you what order it will be; just that it's not 'random' in the non-determinstic sense.

@ChasBrown Good Point. I will remove that constraint altogether. It made more sense with the original long-winded introduction I had, but from a pure technical side there's not much justification and I think I don't want to have to try to adjudicate "good deterministic" from "bad deterministic"

Jelly, 29 bytes
ḟŒPŒ!€Ẏ;ṙ-ɗ€Ḋ⁼Ṗ}ɗƝẠ$ƇLÞṪ;Ṫ}¥/

Try it online!
Golfy, but inefficient answer that generates all combinations of all power sets of the country code set minus the start and end, and then checks which ones fit the rules. A dyadic link that takes as its left argument the set of codes and its right argument the end and start in that order. Returns 0 if no path exists. Otherwise returns the longest path, and if there is more than one, the last as determined by the order of the input set.
Jelly, 42 43 bytes
ṭ@Ɱ⁵ḟṖ⁼¥Ƈ0ị$Ḋ$ƲßẎ;W)
ÇẎ0ị$Ḋ⁼⁴Ṗ¤ƲƇLÞṪṭ@;Ṫ}¥/

Try it online!
A full program that takes three arguments: the starting country in a nested list, the final country and the list of country codes. Returns a Jelly string of the longest path if one exists with the sort order determined by the reverse of the listing of the country codes. If no valid path exists, returns 0 followed by the last letter of the destination. Works recursively, and handles longer cases relatively efficiently.

Python 2, 119 bytes
def f(s,e,c):
 r=max([s[0]+f(p,e,c-{p})for p in c-{s}if s[1:]==p[:2]]+[e]*(s==e)+['!'],key=len)
 return[r,'!']['!'in r]

Try it online!
Takes country codes as a set of strings; returns longest path or ! if no such path exists.

Retina, 108 bytes
+/(?m:^.*\b((..).)(?!.*\1).*\2$)/_L$`\b(..)(.)(?!.*\1\2)(?=.*\1$)
$=$2
mL$`(...),(\w*\1)\w*$
$2
N$^`
$.&
1G`

Try it online! Link includes test suite. Takes input in the order set, terminal, initial. Explanation: Works by generating all possible paths, filtering on those that include the destination, and taking the longest. Explanation:
+

Repeat the command until it does nothing (because there are no more matches).
/(?m:^.*\b((..).)(?!.*\1).*\2$)/_

Operate only on lines whose chain can be extended.
L$`\b(..)(.)(?!.*\1\2)(?=.*\1$)
$=$2

List all of the new possible chains.
mL$`(...),(\w*\1)\w*$
$2

List all of the chains that include the terminal (cut to the length of the terminal).
N$^`
$.&

Sort in ascending order of length, then reverse the list.
1G`

Take the first. In the case of a tie-break, the last to be generated wins; if the set is in lexicographic order then this will be the last in lexicographic order.

JavaScript (ES6), 106 bytes
Takes input as (terminal)(initial,[array of codes]). Returns \$0\$ if there's no solution.
(t,S=0)=>g=(s,a,r=s)=>S=a.map(w=>s[0]+w==s+w[2]&w!=s&&g(w,a.filter(s=>s!=w),r+w[2]))|s!=t||S[r.length]?S:r

Try it online!
Commented
(t, S = 0) =>         // t = terminal code; S = best string, initialized to 0
  g = (               // g is a recursive function taking:
    s,                //   s   = previous code (or initial code on the first call)
    a,                //   a[] = array of codes
    r = s             //   r   = current result string, initialized to the first code
  ) =>                //
    S =               // this code will eventually update S
    a.map(w =>        // for each word w in a[]:
      s[0] + w ==     //   the test w[0] + w[1] == s[1] + s[2] can also be processed
      s + w[2]        //   as s[0] + (w[0] + w[1]) + w[2] == s[0] + (s[1] + s[2]) + w[2]
      &               //   and therefore as s[0] + w == s + w[2]
      w != s &&       //   if the above test is true and w is not equal to s:
      g(              //   do a recursive call to g:
        w,            //     use w as the previous code
        a.filter(s => //     using a[], create a new array:
          s != w      //       where w is removed
        ),            //     end of filter()
        r + w[2]      //     append w[2] to r
      )               //   end of recursive call
    ) |               // end of map()
    s != t ||         // if s is not equal to t
    S[r.length] ?     // or S is longer than r:
      S               //   leave S unchanged
    :                 // else:
      r               //   update it to r

Haskell, 102 95 bytes
import Data.Lists
f l u@(s:t)e=argmax(1<$)$"":[e|e==u]++[s:f(l\\[w])w e|w<-l,t==take 2w,u/=w]

Returns an empty string if no path exists.
As Data.Lists is not installed on TIO, I'm providing a definition for argmax. I'm still importing Data.List for \\, so the code on TIO scores one byte less.  [Try it online!]Try it online!


text:
As programmers say: Strive to be lazy
Story
Have you seen this post from 9gag?
Maybe you got the feeling to make your own sentences. But then you realize that you could just golf a script in half an hour, and you will never have to deal time with that.
The submission
Your program will get an input string which it will return with added quotation marks as explained below.
Standard loopholes are forbidden. Output as a list of lines is allowed. Trailing spaces and empty lines that don't break the output are allowed.
The rules of input

The input only contains printable ASCII characters.
The input may contain spaces. The words are determined with them.
It's guaranteed that a space will never be followed by another space.
The case of no input or empty string doesn't matter.

The rules of output
If one word is given then the program has to return the string between quotation marks.
If the input string has 2 or more words, it first returns the initial input, but the first word is in quotation marks. Then on the next line, it returns the initial input, but with the second word in quotes. And so on for the remaining words.
In general, the program has to return as many lines as there are words in the input.
Examples:
test -> "test"

This is codegolf -> "This" is codegolf
                    This "is" codegolf
                    This is "codegolf"

This is a significantly longer, but not the longest testcase -> "This" is a significantly longer, but not the longest testcase
                                                                This "is" a significantly longer, but not the longest testcase
                                                                This is "a" significantly longer, but not the longest testcase
                                                                This is a "significantly" longer, but not the longest testcase
                                                                This is a significantly "longer," but not the longest testcase
                                                                This is a significantly longer, "but" not the longest testcase
                                                                This is a significantly longer, but "not" the longest testcase
                                                                This is a significantly longer, but not "the" longest testcase
                                                                This is a significantly longer, but not the "longest" testcase
                                                                This is a significantly longer, but not the longest "testcase"

Here is an another one -> "Here" is an another one
                          Here "is" an another one
                          Here is "an" another one
                          Here is an "another" one
                          Here is an another "one"

This is code-golf, so the least byte answer wins!

Will there be duplicate words?

Can we assume the input string will not contain " characters?

Re "Strive to be lazy": I think this is a misrepresentation of what Larry Wall said. - "Most folks see laziness as a synonym for slacker or couch potato, but Wall's definition is about efficiency."

This "problem" should be "fun" to "golf".

Can we use different quotes, like '', ‘’, or “”, rather than ""?

vim, 38 bytes
:s/"/<C-d>/g
qqysW"Ypds"W@qq@qdk:%s/<C-d>/"/g

Try it online!
Requires the vim-surround plugin.
If the input does not contain " characters, this can be done in 19 bytes:
qqysW"Ypds"W@qq@qdk

Here, we record a recursive macro (qq ... @qq@q) that surrounds a word with quotation marks (ysW"), duplicates the line (Yp), deletes the quotation marks (ds"), and moves to the next word (W) before calling itself recursively. After it terminates, there are two extraneous lines, which are deleted with dk.
The full solution simply wraps this with :s/"/<C-d>/g at the beginning, which replaces existing " characters with an unprintable character, and :%s/<C-d>/"/g at the end, which undoes the replacement.

I actually made the examples with the same method :D

Haskell, 65 bytes
([]#).words
a#(b:c)=unwords(a++('"':b++"\""):c):(a++[b])#c
_#_=[]

Returns a list of lines.
Try it online!

This seems to fail when the input contains quotation marks, newlines or other escaped charcters.

It doesn't fix the issue but you could save a byte by removing the tail call optimization

@SriotchilismO'Zaic: fixed. Thanks for pointing out. Regarding the shorter version: xnor already posted this as an answer.

Not quite fixed, since words considers \n to be whitespace it behaves inproperly when it is present.

@SriotchilismO'Zaic: "The input only contains printable ASCII characters", which is Space to ~. "The input may contain spaces" - not "whitespace".

Jelly,  15  14 bytes
Ḳ⁾""j$€⁹¦K¥ⱮJ$

Try it online!
How?
Ḳ⁾""j$€⁹¦K¥ⱮJ$ - Link: list of characters, S
Ḳ              - split (S) at spaces -> A
             $ - last two links as a monad:
           Ɱ   -   map...
            J  -   ...across: range of length -> I = [1,2,...len(A)]
          ¥    -   ...doing: last two links as a dyad: i.e. f(A, i) for i in I
      € ¦      -     sparse application...
       ⁹       -     ...to indices: chain's right argument, i
     $         -     ...action: last two links as a monad:
 ⁾""           -       literal list of characters = ['"', '"']
    j          -       join (with A[i]) -> (e.g. with ['i','s']) ['"','i','s','"']
         K     -     join with spaces

Easy save. (Decided to comment here because you were the first to post similar code. :P)

@EriktheOutgolfer thanks, came back to post a similar improvement myself.

Retina 0.8.2, 17 bytes

" $'¶$` "
^|$
"

Try it online! Link includes test suite. Explanation:

" $'¶$` "

Expand each space by duplicating the line and then inserting quotation marks.
^|$
"

Fix the first and last lines.

JavaScript (ES6),  43 42 41  38 bytes
Saved 3 bytes thanks to @mazzy
Uses the non-standard but widely supported RegExp.leftContext and RegExp.rightContext. That's a lot of different quotes...
s=>s.replace(/(\S+) ?/g,`$\`"$1" $'
`)

Try it online!

Smart! But see on the comma in the test case This is a significantly "longer,"...

Wouldn't /(\S+)/g work?

@mazzy Oh, thanks. I actually did it that way on purpose because I misread the test case with a comma. Now fixed.

@Shaggy I think we need to capture the space so that it doesn't appear in the left context of the next word.

(@Shaggy But your comment brought to light that I forgot to remove the /i. Thanks!)

The code appends tail empty line. Why not add an extra space to the last line? s.replace(/(\S+) ?/g,$\"$1" $'

@mazzy I guess that's fine indeed. Thanks!

The only problem with using just /\S+/g is that it adds a leading space to all but the first line. It's been asked in the comments whether that's allowed.

Java, 235 183 132 bytes
s->{String a[]=s.split(" "),r="",t;for(int l=a.length,i=0,j;i<l;i++,r+="\n")for(j=0;j<l;)r+=(t=i==j?"\"":"")+a[j++]+t+" ";return r;}

-52 bytes by abusing a variety of things (static access, list vs array, print instead of returning, etc. Thanks @ValueInk!)
-51 bytes by beung lazy and letting @KevinCruijssen do the work for me

Try it online

That's some crazy overhead you need for the java.util.Arrays.copyOfRange. If you utilize java.util.List you can use subList for shorter, and print to STDOUT instead of building an array. I got 193 bytes with those ideas, and also abusing the var keyword.

@ValueInk thanks! I also replaced String.join with s.join for those extra IDE warnings (and -10 bytes).

132 bytes

@KevinCruijssen thanks

Beaten with 117 bytes! Your turn ;)

@OlivierGrégoire no thank you :^)

@OlivierGrégoire Challenge accepted and beaten, sir! ;p 71 bytes

@KevinCruijssen Nice! I haven't even thought regex would do the job. Well done ;-)

@OlivierGrégoire Yeah, at first I wasn't sure it was possible. Took a bit of fiddling around with the positive look-behind and look-ahead before I got it to work, which was both annoying and fun to do (and kind of distracting from my actual job-work, haha xD). And the 71 byte version wasn't too efficient I now notice, since I'm now at 62 bytes. :)

Ruby with -an, 53 bytes
The flags -an are read each line and split to $F.
$F.size.times{|i|a=$F.dup;a[i]=?"+a[i]+?";puts a*' '}

Try it online!

First code golf attempt hopefully it's not terrible and hopefully it's not rule breaking
Kotlin, 105 112 147 117 bytes/chars
fun main(a:Array<String>){val q=a[0].split(" ")
q.forEach{println(q.fold(""){i,n->i+if(it==n)"\"$n\" " else n+" "})}}

Try it online!

05AB1E, 14 bytes
ð¡©ε®y…"ÿ"Nǝ}»

Try it online!

+1 byte (and it works for the edge case) thanks to Emigna.
-1 byte thanks to Kevin!

Unfortunately you need to use ð¡ to handle input such as test.

-1 byte by using a map and ».

JavaScript, 91 97 75 78 bytes

f=

t=>t.split` `.map((c,i,a)=>[...a.slice(0,i),`"${c}"`,...a.slice(i+1)].join` `)

// and test
console.log(f("Hello folks and world").join('\n'));

Outputs a list of lines as a JavaScript array. The last entry has a trailing space as allowed in the question. The test code writes each entry to the console on a separate line for demonstration purposes.
Thanks to Shaggy for 19 bytes off and no leading spaces - when the spread operator is used on an empty array to initialize an array literal, no slots are created in the array produced by the spread operator:
let empty = [];
let array = [...empty, value]
//  produces an array of length 1 containing value

(The 91 byte version had a leading space on the first line, the 97 byte version took 6 bytes to remove it.)

78 bytes

The snippet doesn't run because you defined the f function. Otherwise verified. Good job!

@krinistof fixed it, thx!

Words after the quoted word are separated by commas instead of spaces (Firefox, not sure if that's a browser issue)

@wastl Golfed 3 bytes too many and didn't see the commas due to blurry eyes. Putting back the second spread operator (as in Shaggy"s link) removes the commas . Note to self... put my glasses on next time ;-(

Python 3, 79, 69, 65 bytes
w,i=input(),0
while~i:m=w.split();m[i]='"%s"'%m[i];print(*m);i+=1

Try it online!
Shaved 10 bytes thanks to xnor. And now this is 65 bytes as per  Erik the Outgolfer solution. Program ends with IndexError but this is fine.

Terminating with error is fine for programs. A handy trick: you can use print(*l) in Python 3 in place of print(" ".join(l)).

Even better, use Extended Iterable Unpacking.

65 bytes: Instead of assigning w to input().split(), assign it to input(), then, in the while loop, assign m to w.split(), which will create a new list at each iteration to avoid reference issues, then set m[i] to '"%s"'%m[i] and print(*m).

Java 8, 72 71 67 62 bytes
s->s.replaceAll("(?<=(^.*))(\\S+) ?(?=(.*$))","$1\"$2\" $3\n")

Try it online.
Explanation:
s->                    // Method with String as both parameter and return-type
  s.replaceAll("...",  //  Replace all matches in this regex
               "...")  //  With this
                       //  And then return the result

Regex explanation:
(?<=(^.*))(\\S+) ?(?=(.*$))   # === MATCH ===
(?<=     )                    # A positive look-behind to:
     ^.*                      #  The optional leading portion of the string
    (   )                     #  (which is captured in capture group 1)
           \\S+               # Followed by one or more non-space characters,
                              # so the next word in line
          (    )              # (which is captured in capture group 2)
                 ?            # Followed by an optional space
                  (?=     )   # Followed by a positive look-ahead to:
                      .*$     #  The trailing optional portion of the string
                     (   )    #  (which is captured in capture group 3)

$1\"$2\" $3\n                 # === REPLACEMENT ===
$1                            # The match of capture group 1
                              # (the leading portion)
    $2                        # Followed by the match of capture group 2
                              # (the current word in the 'iteration'),
  \"  \"                      # surrounded by quotation marks
                              # Followed by a space character
         $3                   # Followed by the match of capture group 3
                              # (the trailing portion)
           \n                 # Followed by a trailing newline

You have just paved the way for a multitude of regex answers. Well done.

I tried to port this to Python. Sometimes I wish regex parsers were consistent across languages.

@BenjaminUrquhart Unfortunately they aren't.. Java regex is different than C# regex, Python is different again, Perl is different again, etc. Indeed a bit annoying.

Ruby, 98 chars.
First submission ever. This can definitely be shortened. I just wanted to get an answer in quickly.
a=->s{s.split.each_index{|i|puts s.split.each_with_index.map{|a,j|i==j ? "\"#{a}\"":a}.join(" ")}}

Try it online!

Welcome to PPCG! My suggestion would be for each index, save s.split as a variable and edit the index you want to have the quotes around it, instead of using the overly verbose each_with_index.map. Also, you can submit the anonymous lambda without naming it, and join can be replaced with a * operator. This drops your byte count to 64 bytes.

Fantastic! I knew there was a shorter way to do the join, but I was trying to get out of the office and wanted to submit something before leaving XD. I didn't realize the rules allowed for anonymous lambdas like that.

Haskell, 64 bytes
map unwords.g.words
g(h:t)=(('"':h++"\""):t):map(h:)(g t)
g _=[]

Try it online!
Outputs a list of strings. Based on nimi's answer.

This answer like nimi's doesn't work properly when the input contains escaped characters like \n or ".

Perl 6, 43 40 bytes
{m:ex/^(.*?<<)(\S+)(>>.*)$/>>.join('"')}

Try it online!
Matches all possible words, then joins each list by quotes. This could be one byte shorter if we could output lines in reverse order.
Explanation:
{                                      }  # Anonymous code block
 m:ex/^                  $/               # Match all strings
       (.*?)         (.*)                 # Match before and after sections
            <<(\S+)>>                     # And the actual word (with no spaces)
                           >>.join('"')   # And join each line by "s

Reflections, 229 bytes
  _1 +\ /\/(3\  /(0\
/+_:   # \#_: v1=2#_ \
\     /_+/:3; / 1/\:1)
/v(3(2/ \3)(3 ;\#@ \ /
   /:#_(0\:_ / (0*  /0  \
 0 >~    <>~   <0 \  *#_/
 \       /     /\/ v/
   \=2#_1/\2#_>  (0~
                 \ ^\
\                   /

Test it!
I "quickly" "golfed" this in a "funny" "golfing" language.
Looking at all that whitespace, it could probably be shorter.

R, 94 76 bytes
-18 bytes thanks to Giuseppe
m=matrix(s<-scan(,a<-'"'),n<-length(s),n);diag(m)=paste0(a,s,a);write(m,1,n)

Try it online!
Thanks to digEmAll for setting up the TIO properly. It takes in e.g. This is codegolf and outputs correctly
"This" is codegolf
 This "is" codegolf
 This is "codegolf"

It uses a matrix format with the sentence repeated n times; then we only need to change the diagonal entries. Note that usually, in R code-golf, strings are read in with scan(,""), but any string can be used instead of the empty string as the what (or w) parameter.
Explanation of old ungolfed version:

s <- scan(t=scan(,''),w=t)    # read in input and separate by spaces
n <- length(s)                # number of words
m = matrix(s, n, n)           # fill a matrix, one word per entry, each column corresponds to the whole sentence. The sentence is repeated n times.
diag(m) = paste0('"', s, '"') # replace diagonal entries with the corresponding word surrounded by quotes
cat(rbind(m,"\n"))        # add a \n at the end of each column, then print column-wise

76 bytes

@Giuseppe Thanks! How did I not see that I didn't need two calls to scan??

Sometimes you just get into a golfing groove. If we can use other quotes than "", we can reduce to 68 bytes using sQuote.

Stax, 10 bytes
▓¼MY@≈╢∞◙╗

Run and debug it
Unpacked, ungolfed, and commented, it looks like this.
jY      split on spaces and store in y register
m       for each word, run the rest of the program and implicitly output
  '"|S  surround with double quotes
  yia&  start with register y, and replace the ith element, where i is the iteration index
  J     join with spaces

Run this one

JavaScript, 62 bytes
Thanks @Shaggy for golfing off 10 bytes

f=
x=>x.split` `.map((c,i,a)=>(s=[...a],s[i]=`"${c}"`,s.join` `))

console.log(f("Hello folks and world").join('\n'));

Explanation

The function splits the string at each space (x.split` `)
For each element in the resulting array perform the following function
Create a shallow copy of the array (s=[...a])
Replace the nth element in the array with itself surrounded with quotation marks (s[i]=`"${c}"`)
return the shallow copy joined with spaces (s.join` `)

62 bytes

This is my first code golf. hopefully its not shit.
EDIT: got it down to 54 bytes with a better regular expression.
**EDIT 2: per suggestions, fixed a bug and made it shorter **
JavaScript (V8), 46 bytes
t=>t.split(' ').map(v=>t.replace(v,'"'+v+'"'))

Try it online!

If the input contains duplicate words, subsequent copies never get quoted.

Splitting on spaces would be shorter.

@recursive should be fixed.

@Shaggy thanks, i incorporated your suggestion

Still doesn't work for duplicate words

C (gcc), 136 133 bytes
As C's tokenizing functions would mess up the string on future reads, I instead calculate the number and offsets for each word and then finish when the total number of iterations of the outer loop matches the number of words.
i,j=1;f(s,c,t)char*s,*c,*t;{for(i=0;i++<j;puts(""))for(j=0,c=t=s;t;t=c+!!c)printf("%3$s%.*s%s ",(c=index(t,32))-t,t,"\""+!!(i-++j));}

Try it online!

Swapping "\""+!!(i-++j) for i-++j?"":"\"" saves you a byte.

PowerShell, 60 40 36 bytes
-20 bytes inspired by Arnauld
$args-replace'(\S+) ?','$`"$1" $''
'

Try it online!
The result has one extra space and one empty line in the tail.

Powershell, no regexp, 60 bytes
($w=-split$args)|%{$p=++$c
"$($w|%{$q='"'*!--$p
"$q$_$q"})"}

Try it online!
Less golfed:
$words=-split $args                     # split by whitespaces
$words|%{
    $position=++$counter
    $array=$words|%{
        $quotation='"'*!--$position     # empty string or quotation char
        "$quotation$_$quotation"
    }
    "$($array)"                         # equivalent to $array-join' '
}

Neither works if the input words contain tabs or other whitespace. From the challenge, only spaces delimit words.

you are right, of course. But rules are: 1. The input only contains printable ASCII characters., 2. The input may contain spaces. Tabs and other whitespace is not printable ASCII, is not it? :)

I suppose that's true - I was only basing my statement off of the OP's comment here, but that hasn't been edited into the challenge ... so I suppose your submission is fine as it currently is.

Japt, 14 12 bytes
¸£¸hYQ²i1X)¸

Try it
2 bytes saved thanks to Oliver.
¸£¸hYQ²i1X)¸     :Implicit input of string
¸                :Split on spaces
 £               :Map each X at index Y
  ¸              :  Split input on spaces
   hY            :  Set the element at index Y to
     Q           :    Quotation mark
      ²          :    Repeat twice
       i1X       :    Insert X at 0-based index 1

12 bytes

D'oh! Of course! Thanks, @Oliver.

Java (JDK), 104 bytes
t->{var w=t.split(" ");int i=0;for(var s:w){w[i]='"'+s+'"';System.out.println(s.join(" ",w));w[i++]=s;}}

Try it online!

Elm Using recursion, 132,130,121,111,100 99 bytes
Golfed down 9 bytes thanks to Kevin Cruijssen technique
and another 22 bytes were cracked by ASCII-only. Turned to non-tail recursion during the golf.
f b a=case a of
 c::r->String.join" "(b++("\""++c++"\"")::r)::f(b++[c])r
 _->[]
u=f[]<<String.words

Try it online
85 bytes after exposing String functions to the current scope
f b a=case a of
 c::r->join" "(b++("""++c++""")::r)::f(b++[c])r
 _->[]
u=f[]<<words

Ungolfed version (Using tail recursion)
push : List a -> a -> List a
push list el =
    list ++ [ el ]

zip : (List a -> a -> List a -> b) -> List a -> List a -> List b -> List b
zip transform before after mapped =
    case after of
        [] ->
            mapped

        current :: rest ->
            transform before current rest
                |> push mapped
                |> zip transform (push before current) rest

wrap : appendable -> appendable -> appendable
wrap v str =
    v ++ str ++ v

cb : List String -> String -> List String -> String
cb before current rest =
    before ++ wrap "\"" current :: rest
        |> String.join " "

result : List String
result =
    zip cb [] (String.words "This is code golf") []

Try ungolfed

C# (Visual C# Interactive Compiler) with /u:System.Text.RegularExpressions.Regex flag, 59 40 bytes
s=>Replace(s,"(\\S+) ?","$`\"$1\" $'\n")

Port of my Java 8 answer, so look there for an explanation.
-19 bytes by porting @Arnauld's regex, since the $`  and $' are supported in C# .NET.
Try it online.

PowerShell, 70 65 bytes
param($a)$a.Split()|%{$a-replace[regex]"( |^)$_( |$)"," ""$_"" "}

Try it online!
Has test suite in trial. Has 1 leading space on first row, and 1 trailing space on last row. Attempting to refactor.

This doesn't work if you have a duplicate word in the test string.

Charcoal, 19 bytes
Ｅ⪪θ ⪫Ｅ⪪θ ⎇⁼κμ⪫""λλ

Try it online! Link is to verbose version of code. Note: Trailing space. Explanation:
  θ                     Input string
 ⪪                      Split on literal space
Ｅ                       Map over words
       θ                Input string
      ⪪                 Split on literal space
     Ｅ                  Map over words
            μ           Inner index
          ⁼             Equals
           κ            Outer index
         ⎇             If true then
               ""       Literal string `""`
              ⪫         Joined i.e. wrapping
                 λ      Current word
                  λ     Otherwise current word
    ⪫                  Joined with literal space
                        Implicitly print each result on its own line

Attache, 34 bytes
Join&sp=>{On&_&Repr=>Iota@_}@Split

Try it online! Anonymous function returning a list of lines.
Explanation
Join&sp=>{On&_&Repr=>Iota@_}@Split
                             Split      Splits the input on whitespace
         {         =>Iota@_}            Over each number K, 0 to #words - 1
          On  &Repr                     Apply the Repr (quoting) function
            &_                          on the Kth element in the input
Join&sp=>                               then rejoin the words of each inner sentence

Perl 6, 46 bytes
{map {.prematch~"\"$_\""~.postmatch},m:g/\S+/}

Try it online!

The match part can just be m:g/\S+/, and I think the pre/post match part can be shorter too

/\S/ doesn't match the tab character. I'm actually not sure how whitespace other than space should be treated.

The question says printable ASCII, which only includes spaces, not tabs or newlines

C# (Visual C# Interactive Compiler), 123 bytes
I wonder if can this be shortened with regular expressions.

s=>(r=s.Split(' ')).Select((a,i)=>(string.Join(" ",r.Take(i))+" \""+a+"\" "+string.Join(" ",r.Skip(i+1))).Trim());string[]r

Try it online!

118 bytes

110 bytes

Port of Java answer - 104 :)

@dana My port is shorter, though ;)

@KevinCruijssen - I saw you got that regex earlier :) Figured that was a totally different approach so I didn't try porting it over, but yeah that is a good solution!

Jelly, 15 bytes
⁾""j$€⁹¦K
ḲçⱮL$

Try it online!
Thanks to @JonathanAllan for saving 4 bytes

I'm pretty sure you need to count the Y unless you get the OP to allow a list of lines as function output. You can then save 4 like this (although mine is then just a one Link version of that).

@JonathanAllan it says a list of lines is ok as output. I’ve added in your improvements - hope that’s ok. Thanks.

Ah so it does! :)

Red, 113 bytes
func[s][repeat i length? u: split s" "[j: 1
foreach w u[prin rejoin[t: pick[{"}""]i = j w t sp]j: j + 1]prin lf]]

Try it online!

APL+Win, 59 bytes
(⌽⍳⍴s)⊖((¯1 0+⍴s)⍴s)⍪(('"',¨s←(+\' '=s)⊂s←' ',⎕),¨'"')~¨' '

Prompts for string
Try it online! Courtesy of Dyalog Classic

J, 45 bytes
   f =: ' 'joinstring"1(]`(dquote&.>])@.=($~$@=))@cut
   f 'this is a test string'
"this" is a test string
this "is" a test string
this is "a" test string
this is a "test" string
this is a test "string"

If the input can be a list of boxes, then my solution can be 30 bytes:
   f =: (]`(dquote&.>])@.=($~$@=))@cut
   f 'this is a test'
┌──────┬────┬───┬──────┐
│"this"│is  │a  │test  │
├──────┼────┼───┼──────┤
│this  │"is"│a  │test  │
├──────┼────┼───┼──────┤
│this  │is  │"a"│test  │
├──────┼────┼───┼──────┤
│this  │is  │a  │"test"│
└──────┴────┴───┴──────┘

+1 from me, but I think you need to make it a verb to comply with the PPCG rules:
Try it online:

Ah I didn't realize that was a rule. Fixed.

Python 3, 107 bytes
import re
def f(s):
 for w in re.finditer('[^ ]+',s):p=w.span();print(f'{s[:p[0]]}"{w.group()}"{s[p[1]:]}')

Try it online!
I... decided to use regex against my better judgement. This is the result.

Oracle SQL, 92 bytes
select regexp_replace(s,'(\S+)','"\1"',1,level)from t connect by level<regexp_count(s,' ')+2

Assuming there is a table in a form
create table t as select 'This is a significantly longer, but not the longest testcase' s from dual;

Test in SQL*Plus
SQL> select regexp_replace(s,'(\S+)','"\1"',1,level)from t connect by level<regexp_count(s,' ')+2
  2  /

REGEXP_REPLACE(S,'(\S+)','"\1"',1,LEVEL)
--------------------------------------------------------------------------------
"This" is a significantly longer, but not the longest testcase
This "is" a significantly longer, but not the longest testcase
This is "a" significantly longer, but not the longest testcase
This is a "significantly" longer, but not the longest testcase
This is a significantly "longer," but not the longest testcase
This is a significantly longer, "but" not the longest testcase
This is a significantly longer, but "not" the longest testcase
This is a significantly longer, but not "the" longest testcase
This is a significantly longer, but not the "longest" testcase
This is a significantly longer, but not the longest "testcase"

10 rows selected.

SNOBOL4 (CSNOBOL4), 93 bytes
	S =' '
	I =INPUT S
S	I ARB . R S REM . I	:F(END)
	OUTPUT =L '"' R '"' S I
	L =L R S	:(S)
END

Try it online!
Each line ends with an additional space.

Python 3.8 (pre-release), 92, 79 bytes
-13 bytes thanks to @Steffan
lambda x:(l:=range(len(x)),[[[x[a],'"%s"'%x[a]][a==i]for a in l]for i in l])[1]

Try it online!

it would be two less bytes if you yielded instead of printing to stdout

you could actually just use a lambda: Try it online!

Try it online! for 79 bytes with python 3.8

Python 2, 108 bytes
def f(s):
 W=s.split();n=len(W)
 for x in range(n*n):print[W[x%n],'"'+W[x%n]+'"'][x%-~n==0]+'\n'*(x%n==n-1),

Try it online!

PHP, 134 bytes
<?php $i=explode(' ',file_get_contents('php://stdin'));for($x=0;$x<count($i);$x++){$o=$i;$o[$x]='"'.$i[$x].'"';echo join(' ',$o).'
';}

Try it online!

Thunno 2 N, 10 bytes
Oı$OṅnṘȧðj

Try it online!
Explanation
Oı$OṅnṘȧðj  # Implicit input
O           # Split it on spaces
 ı          # Map over this list:
  $O        #  Input split on spaces
    ṅ  ȧ    #  Replace the current item with
     nṘ     #  itself surrounded by quotes
        ðj  #  Join this list on spaces
            # Join on newlines
            # Implicit output

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Extrude the faces of a cube symmetrically along XYZ
Sandbox
For the purposes of the current task, a cube of unit length is rendered in oblique projection with ASCII symbols as follows:
  +-----+
 /     /|
+-----+ |
|     | +
|     |/
+-----+

+ for the vertices.
- for the X edges. The unit length along X is represented by five - between two vertices.
| for the Y edges. The unit length along Y is represented by two | between two vertices.
/ for the Z edges. The unit length along Z is represented by one / between two vertices.
Vertices are only drawn where all the three planes intersect.
Edges are only drawn where exactly two planes intersect.

When a unit face is extruded, it is offset by a unit length from its original position and four new edges are created for each direction (positive and negative).
You can think of the extrusion as of drawing the axes of a 3D Cartesian coordinate system where each axis is represented as a cuboid with cross section 1x1 and length n away from (0,0,0)
Extruded by 1 along X:
  +-----------------+
 /                 /|
+-----------------+ |
|                 | +
|                 |/
+-----------------+

Task
Given three numbers for the XYZ axes, extrude the faces of a unit cube symmetrically by the indicated amounts and render the result with the ASCII symbols as specified above.
Input
x, y, z – non-negative numbers - extrusion lengths for the respective axes. 0 means no extrusion.
The input can be three numbers, a list of three numbers, a triple, a string or anything that’s convenient for you.
Output
The ASCII drawing of the cube after extrusion. Leading and trailing wihtespaces are allowed.
Test cases
X Y Z
0 0 0

  +-----+
 /     /|
+-----+ |
|     | +
|     |/
+-----+

1 0 0

  +-----------------+
 /                 /|
+-----------------+ |
|                 | +
|                 |/
+-----------------+

0 0 1
        +-----+
       /     /|
      /     / |
     /     /  +
    /     /  /
   /     /  /
  +-----+  /
  |     | /
  |     |/
  +-----+

1 1 0

        +-----+
       /     /|
      +-----+ |
  +---|     | +-----+
 /    |     |/     /|
+-----+     +-----+ |
|                 | +
|                 |/
+-----+     +-----+
      |     | +
      |     |/
      +-----+

2 0 1

                +-----+
               /     /|
  +-----------+     +-----------+
 /                             /|
+-----------+     +-----------+ |
|          /     /|           | +
|         +-----+ |           |/
+---------|     | +-----------+
          |     |/
          +-----+

1 1 1

        +-----+
       /     /|-+
      +-----+ |/|
  +---|     | +-----+
 /    |     |/     /|
+-----+-----+-----+ |
|    /     /|     | +
|   +-----+ |     |/
+---|     | +-----+
    |     |/| +
    +-----+ |/
      +-----+

Winning criteria
The shortest solution in bytes in every language wins. Please add a short description of the method used and your code.

Is there an upper bound for each of the extrusions?

@Embodiment of Ignorance - 9 should be enough

JavaScript (ES6),  525 ... 475 471  459 bytes
Saved 13 bytes thanks to @Neil
Takes input as an array [X,Y,Z]. Returns a matrix of characters.
a=>([X,Y,Z]=a,m=[],W=X*6+Z*2,'1uol9h824lsqpq17de52u1okgnv21dnjaww111qmhx1gxf4m50xg6pb42kzijq21xyh34t0h2gueq0qznnza2rrimsg3bkrxfh3yrh0em').replace(/.{7}/g,s=>[[c,x,A,y,B,w,C,h,D,t]=parseInt(s,36)+s,Y*W,Z,X,Y|!W,Z*X,X*Y*!Z,X*Z*!Y,Y*Z*!X][c]&&(g=H=>V<h&&((m[r=y-(3-B)*p+(t>1?H-V:V)+Y*3+Z*2]=m[r]||Array(W*2+9).fill` `)[x-2*(3-A)*p+(t>1?V:H-V*t)+W]=` ${c>5?'  + ':t>1?'|-':'-|'}+/+`[(H%~-w?0:+t?4:2)|!(V%~-h)],g(++H<w?H:!++V)))(V=0,p=a[c%3],w-=-3*C*p,h-=-D*p))&&m

Try it online!
How?
Drawing steps
The output consists of 15 sides, drawn in a specific order.

Implementation
The drawing function is \$g\$. It works with the following parameters:

\$(x, y)\$: where to start drawing
\$w\$: width
\$h\$: height
\$t\$: type of side

The vertices are always drawn. Depending on the value of another parameter \$c\$, the edges are either drawn or erased.
If \$t=0\$, the function draws a front side:
...........      ...........
..+-----+..      ..+     +..
..|     |..  or  ..       ..
..|     |..      ..       ..
..+-----+..      ..+     +..
...........      ...........

If \$t=1\$, it draws a top side:
...........      ...........
...+-----+.      ...+     +.
../     /..  or  ..       ..
.+-----+...      .+     +...
...........      ...........

If \$t=2\$, it draws a right side:
......+....      ......+....
...../|....      .....  ....
....+ |....  or  ....+  ....
....| +....      ....  +....
....|/.....      ....  .....
....+......      ....+......

The coordinates \$(x,y)\$ and the size \$(w,h)\$ of each side either have a constant value or depend on exactly one of the input variables: \$X\$, \$Y\$ or \$Z\$. Besides, each side is drawn if and only if a specific condition is met.
Both the input variable to use and the condition to check are identified with the parameter \$c \in[1..8]\$.
To summarize, a side is fully described with:
$$\begin{cases}
c\\
t\\
x=o_x+m_x\times P\\
y=o_y+m_y\times P\\
w=o_w+m_w\times P\\
h=o_h+m_h\times P
\end{cases}
$$
where \$P\$ is the input variable deduced from \$c\$.
Therefore, we need to store the following 10 parameters for each side:
$$[c, o_x, m_x, o_y, m_y, o_w, m_w, o_h, m_h, t]$$
Below are the parameters of the 15 sides that need to be drawn:
$$\begin{array}{|c|c|}
\hline
\text{side} & c & o_x & m_x & o_y & m_y & o_w & m_w & o_h & m_h & t\\
\hline
0 & 4 & 0 & 0 & 2 & -3 & 7 & 0 & 4 & 6 & 0\\
1 & 4 & 6 & 0 & 2 & -3 & 4 & 6 & 3 & 0 & 2\\
2 & 2 & 6 & -2 & 2 & 2 & 4 & 0 & 3 & 4 & 2\\
3 & 3 & 6 & 6 & 2 & 0 & 4 & 0 & 3 & 0 & 2\\
4 & 3 & 0 & -6 & 2 & 0 & 7 & 12 & 4 & 0 & 0\\
5 & 2 & 2 & 2 & 0 & -2 & 7 & 0 & 3 & 4 & 1\\
6 & 3 & 2 & -6 & 0 & 0 & 7 & 12 & 3 & 0 & 1\\
7 & 2 & 0 & -2 & 2 & 2 & 7 & 0 & 4 & 0 & 0\\
8 & 5 & 6 & -2 & 2 & 2 & 4 & 0 & 1 & 2 & 2\\
9 & 4 & 2 & 0 & 0 & -3 & 7 & 0 & 3 & 0 & 1\\
10 & 1 & 0 & 0 & 2 & -3 & 7 & 0 & 1 & 3 & 0\\
11 & 1 & 6 & 0 & 2 & -3 & 1 & 3 & 3 & 0 & 2\\
12 & 6 & 0 & 0 & 2 & 0 & 7 & 0 & 4 & 0 & 0\\
13 & 7 & 2 & 0 & 0 & 0 & 7 & 0 & 3 & 0 & 1\\
14 & 8 & 6 & 0 & 2 & 0 & 4 & 0 & 3 & 0 & 2\\
\hline
\end{array}$$
We force all values into the range \$[0..9]\$ by applying the following operations:
$$m_x\gets (m_x+6)/2\\
m_y\gets m_y+3\\
m_w\gets m_w/3$$
It results in 15 numbers of exactly 10 decimal digits, which are stored as 15 groups of 7 digits in base 36.
For instance, the first side is encoded as 4032070460 and stored as 1uol9h8.

I think Array(W*2+9).fill` `  saves a byte.

Oops,sorry, my bad, I must of saw it wrong or something. Disregard.

@EmbodimentofIgnorance No worries. :)

Great visualization in addition to your traditionally cool description! Respect!

@GalenIvanov Thank you! I really enjoyed working on this challenge.

You can save 12 bytes by replacing (A-9?6-A:-6) with (6-A-A) and (C-9?C:12) with C*3 after adjusting the encoding appropriately (which I was unable to do, but the base 10 string is 403207046046320423022622540342366234030230023744002240170341320037430120225704005622540122423007030110320701301632011302603237040072303703018632340302).

@Neil The irony here is that I was initially planning to do something like that and decided to use the '12 becomes 9' trick instead for some weird reason (probably related to an earlier version). Thanks a lot. :)

APL (Dyalog Classic), 162 161 132 130 bytes
{' |+/+ +-? ??? ++'[⍉(⊃~∘0)⍤1⍣3⍉↑a↑¨⍨↓(--1-⌊/∘,)2-/1⌽↑⍳⍴a←16|29|1+{2⊥+/¨∊¨=⌿¨⍵(⍉⍵)(⍉↓⍵)}⌺2 2 2{⍉⍤2⍉⌽0,⍵}⍣6↑3/↓2/6⌿1<⍵+.=⍨↑⍳1+2×⍵]}

Try it online!

generate a 3d bool array of unit cubies
replicate each cubie 6 3 2 times along x y z
surround with zeroes
for each 2×2×2 subarray compute a number between 0 and 16 that determines the corresponding output char: (1 + 4*cx + 2*cy + cz) mod 16 where cx,cy,cz are the number of same-value "rods" along axis x,y,z, i.e. vectors along that axis that consist of the same value: 0 0 or 1 1. we make an exception if the subarray is all-zero (or all-one - those don't matter) and we consider its number 0 instead of 28
for each cell compute where the corresponding char should be drawn on screen
for each cell build a transparent (0-padded) matrix that contains only one opaque "pixel"
mix the matrices - at this point we have a 5d array with dimensions inx,iny,inz,outx,outy
reduce the first three axes, keeping only the first non-transparent (≠0) item along them
use a lookup table (a string) to convert the numbers into -|/+

thanks Scott Milner for spotting that some +s rendered as ?s

How do you actually test this? I wanted to try extrusions of 2,3,4 for example, but nothing obvious seemed to work.

the algo is very wasteful, so 2 3 4 runs out of memory, but 2 3 3 is within reach

@Neil i made a small fix and now 2 3 4 works. lost a byte as a side effect :)

An APL solution that's half as long as a Charcoal one on an [tag:ascii-art] challenge?! What's going on?!

@Shaggy apl is great at multi-dim arrays. also, this algorithm turned out to be very suitable for golfing

Not 100% sure, but I'm pretty sure that this isn't desired behavior on 0 1 1

0 1 1 is fixed

Charcoal, 325 bytes
≔×⁶Ｎθ≔×³Ｎη≔⊗Ｎζ¿‹¹№⟦θηζ⟧⁰«Ｂ⁺⁷⊗θ⁺⁴⊗η↗↗⊕⊗ζ+⁺⁵⊗θＰ↙⊗⊕ζ↓+↓⁺²⊗η↙+↙⊕⊗ζ»«Ｆ‹⁰θ«↗+↗←+←⊖θ↙+/Ｐ→θ↓+↓²+⊖θ+»Ｆ‹⁰η«Ｊ⁶¦³↗+↗↓+↓⊖η↙+/Ｐ↑η←+←⁵↑+↑⊖η+»Ｆ‹⁰ζ«Ｊ⁸±²↓+↓↓↗+↗⊖ζ↑+↑²Ｐ↙ζ←+←⁵↙+↙⊖ζ+»Ｊ⁶¦⁰Ｆ‹⁰ζ«Ｇ↓³↙⊕ζ←⁷↑³↗⊕ζ ↙+↙⊖ζ↓+↓²+→⁵Ｐ↗ζ↑+↑²Ｐ←⁶↗+↗⊖ζ»Ｆ‹⁰η«Ｇ←⁶↑⊕η↗³→⁶↓⊕η ↑+↑⊖η←+←⁵↙+/Ｐ↓η+⁵Ｐ↗²↓+↓⊖η»Ｆ‹⁰θ«Ｇ↗²→⊕θ↓⁴↙²←⊕θ →+⊖θ↗+/↑+↑²Ｐ←θ↙+/Ｐ↓³←+←⊖θ»Ｐ↗∧∧θη²Ｐ↓∧∧ζθ³Ｐ←∧∧ηζ⁶+

Try it online! Link is to verbose version of code. Explanation:
≔×⁶Ｎθ≔×³Ｎη≔⊗Ｎζ

Input the extrusions, but premultiply them to save bytes.
¿‹¹№⟦θηζ⟧⁰«Ｂ⁺⁷⊗θ⁺⁴⊗η↗↗⊕⊗ζ+⁺⁵⊗θＰ↙⊗⊕ζ↓+↓⁺²⊗η↙+↙⊕⊗ζ»«

If at least two of the extrusions are zero, then simply draw a cuboid of dimensions (2x+1, 2y+1, 2z+1). Otherwise:
Ｆ‹⁰θ«↗+↗←+←⊖θ↙+/Ｐ→θ↓+↓²+⊖θ+»

Print the left extrusion, if any.
Ｆ‹⁰η«Ｊ⁶¦³↗+↗↓+↓⊖η↙+/Ｐ↑η←+←⁵↑+↑⊖η+»

Print the down extrusion, if any.
Ｆ‹⁰ζ«Ｊ⁸±²↓+↓↓↗+↗⊖ζ↑+↑²Ｐ↙ζ←+←⁵↙+↙⊖ζ+»

Print the back extrusion, if any.
Ｊ⁶¦⁰

The remaining extrusions all meet at this point (which doesn't get drawn until the very end!)
Ｆ‹⁰ζ«Ｇ↓³↙⊕ζ←⁷↑³↗⊕ζ ↙+↙⊖ζ↓+↓²+→⁵Ｐ↗ζ↑+↑²Ｐ←⁶↗+↗⊖ζ»

Print the front extrusion, if any, taking care to erase parts of the left and down extrusions that may overlap.
Ｆ‹⁰η«Ｇ←⁶↑⊕η↗³→⁶↓⊕η ↑+↑⊖η←+←⁵↙+/Ｐ↓η+⁵Ｐ↗²↓+↓⊖η»

Print the up extrusion, if any, taking care to erase parts of the back and left extrusions that may overlap.
Ｆ‹⁰θ«Ｇ↗²→⊕θ↓⁴↙²←⊕θ →+⊖θ↗+/↑+↑²Ｐ←θ↙+/Ｐ↓³←+←⊖θ»

Print the right extrusion, if any, taking care to erase parts of the down and back extrusions that may overlap.
Ｐ↗∧∧θη²Ｐ↓∧∧ζθ³Ｐ←∧∧ηζ⁶+

Draw the joins between the latter extrusions.

325 bytes in Charcoal?! On an [tag:ascii-art] challenge?! That's enough to make me not even attempt this in Ja(vaScri)pt!

@Shaggy This might not be an optimal approach, and there might be ways of golfing it that I've overlooked anyway. I do have to say though that ngn's method looks intriguing, it looks as if he draws the shape into an internal array and then performs edge detection to generate his output.

@Shaggy I've come up with a 195 byte solution, which I've posted separately as it's a completely different approach. Still well short of APL though.

Charcoal, 195 164 144 bytes
≔⁺³×⁶Ｎθ≔⁺²×³Ｎη≔⊕⊗ＮζＦ…·±ζζＦ…·±ηηＦ…·±θθ«Ｊ⁻λι⁺κι≔⟦⟧δＦＥ²↔⁻⁺ιμ·⁵ＦＥ²↔⁻κνＦＥ²↔⁻⁺λξ·⁵⊞δ⌊⟦‹μζ‹νη‹ξθ‹¹№Ｅ⟦μνξ⟧‹π⊕ρ¹⟧≡Σδ¹+²§ |-/⁺⌕δ¹⌕⮌δ¹¦³+⁴§ +Σ…δ⁴¦⁶§ |-/⌕δ⁰

Try it online! Link is to verbose version of code. I'm posting this as a separate answer as it uses a completely different approach to drawing the extrusion. Explanation:
≔⁺³×⁶Ｎθ≔⁺²×³Ｎη≔⊕⊗Ｎζ

Input the extrusions and calculate half the size of the enclosing cuboid, but in integer arithmetic because Charcoal's ranges are always integers. The origin of the output maps to the centre of the original unit cube.
Ｆ…·±ζζＦ…·±ηηＦ…·±θθ«

Loop over all coordinates within (including the boundary) the cuboid containing the extrusion.
Ｊ⁻λι⁺κι

Jump to the output position corresponding to those coordinates.
≔⟦⟧δＦＥ²↔⁻⁺ιμ·⁵ＦＥ²↔⁻κνＦＥ²↔⁻⁺λξ·⁵⊞δ⌊⟦‹μζ‹νη‹ξθ‹¹№Ｅ⟦μνξ⟧‹π⊕ρ¹⟧

From the given coordinates, peek in all eight diagonal directions to determine whether the extrusion overlaps in that direction. The peeked coordinates are checked that they still lie within the cuboid, and then the number of axes in which the coordinate lies within the original cube must be greater than 1. Note that since the cube has an odd display height, the Y-axis values that are peeked are integers while the other axes use fractional coordinates.
≡Σδ

Consider the number of directions in which the extrusion overlaps. There are five cases of interest where we want to print something, as in the case of zero, that means that this is empty space and we don't want to print anything, while in the case of eight, that means that this is inside the extrusion and anything we did print would be overprinted by a layer nearer the eye point.
¹+

If the extrusion only overlaps in one direction then this is an outer corner and we need to output a +.
²§ |-/⁺⌕δ¹⌕⮌δ¹¦

If the extrusion overlaps in two directions then this is an outer edge. Which sort of edge is determined from the separation between the two overlaps; 6 and 7 are rear-facing edges and will get overwritten, 4 is a diagonal edge, 2 is a vertical edge and 1 is a horizontal edge. (I actually calculate 7 minus the separation as it seems to be easier to do.)
³+

If the extrusion overlaps in three directions then this is an inner corner in the case where one of the extrusions is zero and we need to output a +.
⁴§ +Σ…δ⁴¦

If the extrusion overlaps in four directions then there are two cases: faces (any direction), and inner corners in the case with three positive extrusions. In the latter case there are an odd number of overlaps towards the viewer.
⁶§ |-/⌕δ⁰

If the extrusion overlaps in six directions then this is an inner edge. It works like the complement of an outer edge except that we're only interested when one of the two empty spaces is the direction towards the eye point (the last entry in the array).

K (ngn/k), 172 bytes
{s:1+|/'i-:&//i:1_--':1_4#!#'2*:\a:16!29!1+2/(!3){+'+x}/'{2+':''1+':'0=':x}'{++'x}\6{+'+0,|x}/{6}#{3}#'{2}#''s#1<+/x=!s:1+2*x;" |+/+ +-? ??? ++"s#@[&*/s;s/i;{x+y*~x};,//a]}

Try it online!
obligatory k rewrite of my apl solution
same algorithm, except that 3d->2d rendering is done with (the k equivalent of) scatter index assignment instead of creating 2d matrices for each 3d element and mixing them

How would your ngn/apl perfrom in comparison to your Dyalog APL solution?

@GalenIvanov it wouldn't be a fair comparison because in my apl solution i waste a lot of memory to save a few bytes, and in k shorter happens to be faster in this case

I asked about comparison between two APL solutions -  yours APL/Dyalog one and a hypothetical solution in ngn/apl

oops, i don't know why i read that as "ngn/k"... it's again unfair - ngn/apl is hobbyist javascript, dyalog is professional c

Sorry, I didn't mean perform in terms of speed, but as codegolf - would it be shorter?

@GalenIvanov probably not. ngn/apl is missing recent additions to the language like the rank operator (⍤) and stencil (⌺)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Building a Structured Outline
In a fictional document management system, input documents are structured with weighted headings. Lowest weighted headings are the most important.
This is a sample document:
H1 All About Birds
H2 Kinds of Birds
H3 The Finch
H3 The Swan
H2 Habitats
H3 Wetlands
From this document we would like to produce an outline using nested ordered lists in HTML, which would look like this when rendered:

All About Birds

Kinds of Birds

The Finch
The Swan

Habitats

Wetlands

Your code only needs to take the input list and transform it into the expected data structure, which will be printed.

When you say "using nested ordered lists in HTML" do you mean we need to produce HTML? If so could you define its form for us? (Or may we just indent using a space (or a tab?)?)

Can the titles be assumed to only contain letters and spaces?

Hi and welcome to codegolf! To avoid having to answer questions like those you received,  please note that we have a sandbox for proposed challenges which allows you to receive feedback before posting. As is you are missing a few important details, like those already asked about, and things like what the highest header level there will be (or if it is indefinite).

This feels familiar; I think we may have had this already using Markdown's # instead of HTML's <h.

@Shaggy except this seems to be about using nested ordered lists
 rather than headings.

May the level be greater than $9$?

Are we guaranteed to always have level $L+1$ between levels $L$ and $L+2$? Are we supposed to return valid HTML? (with all trailing
 tags)

Jelly, 53 50 bytes
Ḋœṡ¥€⁶ZµḢVØ0jI>0ẋ"AƲị“
“
”żṪ“
“
”jⱮƊ

Try it online!
A monadic link taking a list of strings as input and outputting an HTML fragment with nested ordered lists. Should handle arbitrarily deep nesting of lists and return a syntactically valid HTML fragment.
Example:
H1 All About Birds
H2 Kinds of Birds
H3 The Finch
H3 The Swan
H2 Habitats
H3 Wetlands
H4 Types of wetlands
H5 Very wet wetland
H3 Coast
H1 All about fish
H2 Sharks

yields:

All About Birds

Kinds of Birds

The Finch

The Swan

Habitats

Wetlands

Types of wetlands

Very wet wetland

Coast

All about fish

Sharks

All About BirdsKinds of BirdsThe FinchThe SwanHabitatsWetlandsTypes of wetlandsVery wet wetlandCoastAll about fishSharks


text:
Automatically anti-predictably assemble an alliterative aria
Thanks to @ComradeSparklePony for the title.
This challenge should be very simple. You are given three lists.
The first is a list of first names, in title case.
The second is a list of adjectives, in lower case.
The third is a list of nouns, in lower case.
Please randomly select a name, optional adjective, and noun, and output <Name>'s <adjective> <noun>. However, each word must begin with the same letter. You can assume that all words begin with a letter. You can also assume (but note in your answer if you do):

that all words are composed solely of alphabetic characters
that there is at least one noun for each name
that there is at least one name for each noun

You cannot however assume that an adjective exists for a particular pair of name and noun, as the adjective is optional so the output will still be valid.
You do not have to select the shared letter uniformly, although all available letters must have a non-zero chance of occurring. You must however ensure that all outputs for a given letter have as near equal chance of occurring as possible within the limits of your language's random number generator. In the case of the adjective, this is equivalent to having an extra entry meaning "no adjective for this letter" which has the same chance as all of the other adjectives for that letter.
Example input lists:
Joan Neil Nicola Oswald Sherman Stephanie
new novel old original second silent
jeep noun novel output second sheep snake

Example outputs for these inputs (each line is a separate example):
Stephanie's second second
Sherman's silent snake
Oswald's original output
Nicola's novel novel
Neil's noun
Joan's jeep

Note no extra space between words in the last two examples.
This is code-golf, so the shortest code that breaks no standard loopholes wins!
In the unlikely event that it helps, you can input everything in upper case, but you still need to output in sentence case.

Are we correct to assume that the program should return: 1 name 1 adjective (if one matches the name) 1 noun  ?   Or are you asking to produce an output for each name?

Maybe you should add 'Joan' and 'jeep' in your example to illustrate the fact that there might be no adjective at all for a given letter?

Given your example input is the chance of no adjective 1 in 3 (since all adjective "lists" are 2 long)? ...and if 'Joan' and 'Jeep' were also there with no j-adjective would the chance become 4 in 9? Might be worth placing probabilities against outputs, or enumerating all outputs -- as I understand it not only "all outputs for a given letter..." but also all distinct outputs should have equal likelihood (given distinct values within each list).

@DavidC Sorry, I realise adding extra examples has made that unclear; you only produce one line of output for each invocation.

@JonathanAllan Adding "Joan" and "jeep" wouldn't affect the relative chances of "Neil's noun" being output compared with other options containing "Neil" and "noun".

@JonathanAllan As it happens, the example does indeed have a chance of no adjective of 1 in 3, although I hadn't intended it that way. Adding "Joan" and "jeep" would alter the chance of no adjective depending on how frequently the letter "j" was chosen, so it's not necessarily 4 in 9.

I was talking about the chance of any output with no adjective.

"so it's not necessarily 4 in 9" ...so we don't have to be uniform in our choices of name?

@JonathanAllan You only have to be uniform in your choice between different names that start with the same letter. You don't have to be uniform in your choice of letter.

Right, I see (and now see it in the text), thanks for the clarification!

Are we allowed an extra space between the words if there is no adjective?

@NickKennedy No, sorry if that wasn't clear from the example.

Jelly,  27 25  24 bytes
-1 thanks to Erik the Outgolfer (use a zero instead of a space character)
Ż€2¦Œpḟ€0ZḢŒuEƲƇXż“'s“”K

A full program accepting an argument in the form of a Python formatted list of lists of strings which prints the output to STDOUTt.
Try it online!
How?
Ż€2¦Œpḟ€0ZḢŒuEƲƇXż“'s“”K - Main Link: list of lists of lists of characters
 € ¦                     - sparse application...
  2                      - ...to indices: [2]
Ż                        - ...action: prepend a zero (place holder for no adjective)
    Œp                   - Cartesian product (all choices, including invalid ones)
       €                 - for each:
      ḟ 0                -   filter out any zeros
               Ƈ         - filter keep those for which:
              Ʋ          -   last four links as a monad:
         Z               -     transpose
          Ḣ              -     head
           Œu            -     upper-case
             E           -     all equal?
                X        - random (uniform) choice  e.g. [['B','o','b'],['b','l','u','e'],['b','a','g']]
                 ż       - zip with:
                  “'s“”  -   list [["'", 's'], []]       [[['B','o','b'],["'", 's']],[['b','l','u','e'],[]],['b','a','g']]
                       K - join with spaces              [['B','o','b'],["'", 's'],' ',['b','l','u','e'],[],' ','b','a','g']
                         - implicit (smashing) print     Bob's blue bag

24 bytes.

Ah yeah, nice :)

05AB1E,  24 23  21 bytes
Assumes there is a noun for each name, as allowed by the challenge.
„'s«I¯ªâIâ€˜ʒl€нË}Ωðý

Try it online!
Explanation
„'s«                    # append "'s" to all names in the name-list
    I¯ª                 # append an empty list to the adjective-list
       â                # cartesian product between the lists
        Iâ              # cartesian product with the noun-list
          €˜            # deep flatten each sublist
            ʒ    }      # filter, keep only lists that when
             l          # converted to lowercase
              €н        # with only heads kept
                Ë       # have all elements equal
                  Ω     # pick a valid list uniformly at random
                   ðý   # and join by spaces

Oh, the ¯ª and €˜ are smart! I had a 26 byte answer, but was having trouble fixing the double-space when there isn't an adjective..

@KevinCruijssen: Yeah that was the part I had the most issues with as well. Took me a while to realize that I could use ¯ instead of filling with empty strings I had to manually clean up later.

R, 155 148 bytes
-7 bytes thanks to Giuseppe (using * for sample)
function(x,y,z){`*`=sample
while(T)T=length(unique(c(tolower(substr(c(a<-x*1,b<-c(y,"")*1,c<-z*1),1,1)),"")))-2
paste0(a,"'s ",b,if(nchar(b))" ",c)}

Try it online!
Uses rejection sampling: draw at random a name, an adjective (possibly the empty string) and a noun until the first letters match. This condition is checked by counting if the number of unique elements in the vector formed of the first letters, plus the empty string, is of length 2 - this allows for an empty adjective.
Then print the result, with an extra space if the adjective is non-empty.
The different possibilities starting with the same letter have equal occurrence probabilities, since sample draws from the uniform distribution. The easiest way to see this is to condition on the event that the name and noun start with the same letter (which is fine: if they don't, we would reject). Now condition on the event that we accept: this means we draw either the empty adjective, or an adjective starting with the same letter. Each of these possibilities still has equal probability.
Check the probabilities on \$10^5\$ replicates.

Does this have an equal chance of an empty adjective to each other possibility for any given first letter?

@NickKennedy Yes, since sample draws from the uniform distribution. The easiest way to see this is to condition on the event that the name and noun start with the same letter (which is fine: if they don't, we would reject). Now condition on the event that we accept: this means we draw either the empty adjective, or an adjective starting with the same letter. Each of these possibilities still has equal probability.

@NickKennedy Thanks, I'll add that explanation to the post along with a link to verify empirically that the probabilities are equal.

148 bytes

JavaScript (ES6),  139 124 122  120 bytes
Save 2 bytes thanks to @Neil
Takes input as (names,adjectives)(nouns).
(N,a)=>F=n=>/^(.)\S+( \1\S+)+$/i.test(s=(g=a=>a[Math.random()*a.length|0])(N)+"'s "+[(o=g([,...a]))&&o+' ']+g(n))?s:F(n)

Try it online!
Or check the distribution on 5 million draws
How?
The helper function \$g\$ takes an array and returns a random element from this  array, with a uniform distribution.
g = a => a[Math.random() * a.length | 0]

By invoking \$g\$ three times, we generate a random string \$s\$ with a valid format, but without taking the initial letters into account. For the adjective, we append an empty entry and make sure not to insert a trailing space if it's chosen.
s = g(N) + "'s " +
    [(o = g([, ...a])) && o + ' '] +
    g(n)

We then check if all initial letters are identical with the following regular expression:
/^(.)\S+( \1\S+)+$/i

It not, we simply try again until \$s\$ is valid.

+[(o=g([,...a]))&&o+' ']+ saves 2 bytes, I think?

@Neil Ah, yes. Nice one.

Python 3,  161 154 151 147 145 bytes
(Thanks ArBo, EmbodimentOfIgnorance, Neil who have contributed 2, 3 and 4 bytes to my first golf!)
from random import*
c=choice
def f(N,a,n):
 s=c(N);w=s[0].lower();o=N
 while o[0]!=w:o=c(n)
 print(s+"'s",c([x+" "for x in a if x[0]==w]+[""])+o)

Try it online! (with 500k executions)

Takes three lists as inputs.
Assumes at least one noun for each name.

Same score, more golf-y:
Python 3, 145 bytes
from random import*
c=choice
def f(N,a,n):
 s=c(N);y=lambda p,e=[]:c([x+" "for x in p if x[0]==s[0].lower()]+e);print(s+"'s",y(a,[""])+y(n)[:-1])

Try it online! (with 500k executions)
It's just 140 if trailing whitespaces are allowed (by removing square face [:-1])

Nice first answer! You can save a byte in the first while loop: while t>""<t[0]!=w. You can also replace the last line by print(s+"'s",t+(t and" ")+o), dropping the u= in the third line.

I ended up changing my solution because the previous didn't fit the requirements

152 bytes (Footer removed to fit URL in comment)

You're only using the variable t once so you can save 4 bytes by inlining the code. I think you can switch o to use a similar code pattern to t, and then save another 4 bytes by inlining that too.

Thanks, you guys are really helping! @Neil, I haven't be able to refactor o: I reach this: from random import* c=choice def f(N,a,n): s=c(N);y=lambda p,e=[]:c([x for x in p if x[0]==s[0].lower()]+e);print(s+"'s",y(a,[""])+y(n)) (137) but adding the conditional whitespace, via an optional arg to y, costs me 11 bytes

Somehow made it :)

You don't need to indent the function body in your second version :)

And you can save one more byte by switching to *args notation in your lambda:
def f(N,a,n):s=c(N);y=lambda p,*e:c([x+" "for x in p if x[0]==s[0].lower()]+[*e]);print(s+"'s",y(a,"")+y(n)[:-1])

I think I had def f(N,a,n):s=c(N);w=s[0].lower();print(s+"'s",c([x+" "for x in a if x[0]==w]+[""])+c([x for x in a if x[0]==w])).

at what point accepting suggestions becomes straight up cheating? :D

I think removing the [:-1] results in an even better answer: def f(N,a,n):s=c(N);y=lambda p,e=[]:c([" "+x for x in p if x[0]==s[0].lower()]+e);print(s+"'s"+y(a,[""])+y(n))

Vyxal, 39 bytes
℅‛'s+:→a\ ?'h←a⇩h=;``J℅\ ?'h←a⇩h=;℅++++

Finally figured out what I'm doing.
Try it Online!

You might find using the register shorter than using variables

@lyxal I'm not entirely sure how to do that in the filter lambda.

Oh well if it is in a lambda, you can simply use the context variable (n)

@lyxal But I need to check that the previous's first character is the same as the current first character, which I can't do without variables. The context is the current, but there's no way to get the previous.

Ah, I see. Never mind me lol

Jelly, 28 bytes
1ịZḢXɓŒuḢ=ɗƇ€Ż€2¦X€ḟ0ż“'s“”K

Try it online!
Wrote this before I saw @JonathanAllan’s shorter answer, but thought it worth posting since it uses a different approach. Saved 3 bytes by @EriktheOutgolfer’s suggestion on that answer.
A full program taking a list of lists of strings and implicitly printing a randomly selected alliteration. Assumes at least one noun per name.

C# (Visual C# Interactive Compiler), 176 bytes
(a,b,c)=>(a=a[z.Next(a.Count)])+"'s "+b.Where(x=>(x[0]&95)==a[0]).Append("").OrderBy(x=>z.Next()).Last()+" "+c.OrderBy(x=>z.Next()).Last(x=>(x[0]&95)==a[0]);var z=new Random();

Try it online!

You can assume names begin with an uppercase letter, so you can just uppercase the other letters for the comparison, which should save you 10 bytes?

@Neil Yep, exactly 10 bytes :)

Red, 179 bytes
func[a b c][random a random c
foreach k c[if k/1 = h: a/1/1 + 32[g: rejoin[sp k]]]collect/into[foreach
d b[if d/1 = h[keep rejoin[sp d]]]]e: copy[""]random e rejoin[a/1"'s"e/1 g]]

Try it online!
Explanation:
Red[]
f: func[a b c][                     ; a function with 3 arguments
    random a                        ; shuffle the list of names in place
    random c                        ; shuffle the list of nouns in place
    foreach k c [                   ; for each item in the shuffled list of nouns
        if k/1 = h: a/1/1 + 32 [    ; check if it begins with the same lowercase letter
                                    ; as the first name in the shuffled list of names
            g: rejoin [" " k]       ; if yes, then insert a " " in front of it save it as g
        ]                           ; thus I always get the last match
    ]
    collect/into [                  ; collect in a new list e
        foreach d b [               ; all items form the adjectives list
            if d/1 = h [            ; that start with the same lowercase letter as the 1st noun
                keep rejoin [" " d] ; insert a " " in form of the adjective
            ]
        ]
    ] e: copy[""]                   ; the list initially has a single item - the empty string
   random e                         ; shuffle the extracted adjectives list
   rejoin [a/1 "'s" e/1 g]          ; return the formatted string
]

Scala, 234 226 234 206 bytes
-28 due to the fact I thought it had to accept StdIn, it's a function now
def f(a:List[String],b:List[String],c:List[String])=scala.util.Random.shuffle(for(d<-a;e<-("" +: b);g<-c;if(d.head.toLower==g.head&&(e.isEmpty||e.head==g.head))) yield s"$d's $e $g".replace("  ", " ")).head

Try it online!
Ungolfed:
def f(names: List[String], adjectives: List[String], nouns: List[String]) = {
  val allPossible = for {
    name <- names
    adjective <- ("" +: adjectives) // Add the choice of no adjective
    noun <- nouns
    if (name.head.toLower == noun.head && (adjective.isEmpty || adjective.head == noun.head)) // Filter out so only matching entries remain
  } yield
    s"$name's $adjective $noun"
      .replace("  ", " ") // Get rid of artifact created by the empty adjective selection

  scala.util.Random.shuffle(allPossible.toList).head // Get a random element
}

140 bytes. You can use a simple lambda instead of a proper method. There were also some other small modifications to be made (head can be (0) almost everywhere, you can use Seq instead of List (although that doesn't matter since it's not a method anymore), isEmpty can be .size<1, you can use infix syntax for replace)

Actually, =="" can be used for isempty

Icon, 167 163 bytes
procedure f(a,b,c)
!a:=:?a&\x;!c:=:?c&\x;d:=[""]
e:=!b&e[1]==(t:=char(32+ord(a[1,1])))&put(d," "||e)&\x
!d:=:?d&\x;return(!a||"'s"||!d||" "||(k:=!c&t==k[1]&k))
end

Try it online!
Uses the same algorithm as my Red answer.

Ruby, 94 bytes
->a,b,c{"#{n=a.sample}'s #{s=[p,*b.grep(r=/^#{n[0]}/i)].sample;s+" "if s}#{c.grep(r).sample}"}

Try it online!

Excel, 201 bytes
=LET(a,INDEX(A:A,INT(RAND()*COUNTA(A:A))+1)&"'s",f,LEFT(a),b,FILTER(B:B,LEFT(B:B)=f,""),y,INT(RAND()*(ROWS(b)+1)),c,FILTER(C:C,LEFT(C:C)=f),a&IF(y," "&INDEX(b,y),"")&" "&INDEX(c,INT(RAND()*ROWS(c))+1))

Link to Spreadsheet
Explanation
=LET(
a,INDEX(A:A,INT(RAND()*COUNTA(A:A))+1)&"'s", 'a = rand name from first list & "'s"
f,LEFT(a),                                   'f = first letter of a
b,FILTER(B:B,LEFT(B:B)=f,""),                'b = all items in second list starting with f
y,INT(RAND()*(ROWS(b)+1)),                   'y = rand from {0 .. size b}
c,FILTER(C:C,LEFT(C:C)=f),                   'c = all items in third list starting with f
a                                            'result = a
&IF(y," "&INDEX(b,y),"")                     '    & if y = 0 then "" else " " & b(y)
&" "&INDEX(c,INT(RAND()*ROWS(c))+1))         '    & " " & random item from c


text:
Program which behaves differently in/out of a debugger
The challenge is to write a deterministic program (any language/OS) which takes no arguments or other input and behaves differently in a debugger from how it behaves when not being debugged.
For example, the program may output something when being debugged but not output anything when not being debugged. Or output something different in each case. Or it may crash when being debugged but not crash when not being debugged. Or vice-versa.
Caveats and clarifications:

Timing differences do not count.
Interpreted languages are permitted.
To emphasize determinism: the behaviour must be exactly reproducible both in and out of debugging context.
The presence of the debugger itself should the only difference between the two cases.

Telling the debugger to add inputs (stdin or argv ENV or whatever) is cheating, the debugger should run the program "as-is".
Changing the environment (e.g. running in a virtual machine or different OS, or changing OS settings such as memory limits) between debug and non-debug runs is not permitted.

Shortest code wins. I may award a bounty which reveals something interesting about how debuggers work.

Some debuggers output different text on startup to the normal compiler, thus any program seems to meet these conditions.  Does that count?

If it's the debugger producing the output and not the program itself then no.

Doesn't all output come from the debugger?  It's not clear to me what debugger output is vs. program output if we are making a distinction.

Define debugger?

What do you mean by debugger? Which one?

How do you define a debugger? If a language interpreter supports a "debug" mode (which, say, introduces nonstandard commands), does that count?

This reminds me the one time when I spent hours trying to figure out why a C++ program was finishing nearly instantly when not debugget, yet took several minutes to do its work while under a debugger. Turns out that when it was debugged, the default memory allocator took some extra care when allocating/freeing memory, and that particular program was creating an array of thousands of elements (each allocated with an individual new() call) which in the end added up.

Question is on hold because it's unclear what is being asked? Really? The first sentence outlines the requirements in black and white, no? Perhaps those putting the question on hold can clarify why they find it ambiguous rather than a link to a generic "it's unclear" message?

I'm voting to reopen this challenge. Yes I see there are open questions but in my opinion it's very clear what is being asked. The parts that are perhaps unclear are specific points of validity/invalidity. I personally have a bit of a disclaimer in my answer since it only detects if the program is running in debug mode and not whether a debugger is actually debugging it. I'm fully aware that I may need to delete this answer if it turns out that's not okay but it seems to have been received alright by the voting community so far.

x86 and x64_64 machine language on Linux and OSX, 1 byte
0x0:  CC    int3

Try it online!
int 3 throws a SIGTRAP which will cause a debugger to stop as if it encountered a breakpoint. Outside of a debugger, the kernel terminates the process (thanks to @Ruslan for the correction).
C (gcc) (x86 Linux and OSX), 14 11 9 bytes
main=204;

Try it online!
The integer 204 corresponds to the int 3 instruction; the TIO link is the same as above.

clear assignment in the C code, haven't seen that before.

Actually SIGTRAP doesn't result in SIGABRT, so the part about calling abort() is wrong. There's simply no default signal handler for SIGTRAP, so the kernel terminates the process (and the parent can use WIFSIGNALED to detect this and WTERMSIG to determine which signal happened).

APL (Dyalog Unicode), 0 bytes
In Dyalog APL, debugger vs no debugger is choosen by running one's workspace in either the IDE interpreter or the runtime interpreter.
Loading a completely empty default settings workspace into the IDE interpreter, immediately drops the user into REPL mode as applications must actively shut down the interpreter for it to quit:

However, the runtime interpreter does not have a REPL mode, and so if an application comes to an end (for example because it is completely empty) and does not explicitly shut down the interpreter, it implicitly has attempted to reach REPL mode ("the APL session"), and complains:

JavaScript on Firefox, 69 bytes
WARNING: This script may hang your browser! Do NOT test it with other browsers (e.g. Chrome) as it may crash your tab / browser.

for(console.log(a={},i=99);--i;a=a.a={k:new Int8Array(1e9)});alert(1)

How: When debugger is enabled with console tab activated. console.log makes memory leak possible, and the program will run out of memory soon. When debugger is disabled, GC would clear memory allocated, and you would see an alert with text 1 finally.

MSVC (64-bit), 50 35 bytes
main(){return IsDebuggerPresent();}

Exits with code 0 normally but 1 under the debugger (note that WinDbg does not automatically display the exit code but you can fake it by examining the stack). Edit: Saved 15 bytes thanks to @Ruslan.

Does MSVC require prototypes? You might then want to try with MinGW in C89 mode, to save some bytes.

@Ruslan Bah, shows how long it's been since I've used C...

T-SQL, 6 bytes
sp_who

Always returns an extra row under the executing user's name when the debugger is active.

Python, 29 bytes
import sys
sys.modules['pdb']

Without debugger (python3 /tmp/foo.py):
Traceback (most recent call last):
  File "/tmp/foo.py", line 2, in <module>
    sys.modules['pdb']
KeyError: 'pdb'

With debugger (python3 -m pdb /tmp/foo.py):
(empty output)

because pdb is loaded into an app-visible module in the second case.

Java, 131 102 100 bytes
v->(java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments()+"").split(":jdwp")

When running without a debugger this function returns an array of length 1. When running with a debugger, this returns an array of length 2 (greater than 1).
Try it online!
This technically detects if you could attach a debugger; not if one is currently connected... Not sure if that's valid
-23 bytes thanks to Olivier Grégoire for mentioning that I can cut down on what I search for in the runtime parameters and for lambda-izing my answer
-5 bytes thanks to Benjamin Urquhart for noting that calling toString is dumb when I can let Java implicitly convert
-2 bytes thanks to Benjamin Urquhart for changing the return type

You can shorten it using a lambda. Also, it's very likely that you can test only on :jdwp, instead of -agentlib:jdwp. The : is to distinguish runjdwp from -agentlib:jdwp. 108 bytes

103 bytes

@BenjaminUrquhart I feel dumb for missing the toString enhancement here. Good catch!

100 bytes - returns array of length 1 when no debugger is active, array of length at least 2 if there can be one.

JavaScript, 17 bytes

debugger
alert(1)

debugger stops execution if the debugger console is open, else it does nothing

Robotalk, 22 bytes
debug l: chronon l ifg

If the debugger is active, the debug instruction pauses execution until the end of the current game tick.  In this case, the variable "chronon" is always 1 or greater when read, and the program executes an infinite loop.  If the debugger isn't active, debug is a one-cycle no-op.  "Chronon" is now 0 when read, the "ifg" branch isn't taken, and execution reaches the end of the code, which is an error condition.

MATLAB, 6 bytes
dbquit
When stopped in the debugger, this will quit debugging mode.
When not under debug, it will print an error message that it cannot be used when not stopped in the debugger.
It should be noted this only works for evaluation in the command window (one of the three ways of running MATLAB code). It won't work in a function or script as once you try to run the script or function, you stop being in debug mode during execution.
The closest you can get to something that will run in a function/script as well would be:
MATLAB, 22 bytes
feature('IsDebugMode')

This is an undocumented command in MATLAB. If you are stopped in the debugger in a script or function, and then call another function (or command evaluation) that contains the above line, it will return true.
Outside the debugger it will return false.
If you were however to just run a script/function containing the above, even if you add a breakpoint at the start of the script/function and step through, it will return false, because again, once you start executing you stop being in the debugger temporarily.