## Token Save Flow (reusable)

<!-- toc -->
- [Token Save Flow (reusable)](#token-save-flow-reusable)
- [Step 3.5  -  Host Prompt (embedded in Token Save Flow)](#step-35---host-prompt-embedded-in-token-save-flow)
- [Step 3.7  -  Repository read binding (embedded in Token Save Flow)](#step-37---repository-read-binding-embedded-in-token-save-flow)
- [Sequential onboarding loop (Step 3)](#sequential-onboarding-loop-step-3)
- [Identity learning (Step 3)](#identity-learning-step-3)
- [Inline Token Save Pattern](#inline-token-save-pattern)
<!-- /toc -->

This flow is used in TWO contexts:
- **Setup Step 4**  -  for missing tokens during first-time onboarding
- **Phase 0 token pre-check**  -  when a token is missing or expired (401/403) at runtime

**Trigger**: token missing (`keychainMapping` is `null`) OR token expired (API returned 401/403).

**Step A  -  Ask** (options depend on whether the token is missing or expired):

Missing token (first-time / unmapped):
```
{Service} token missing.
  Where to get it: {source URL/instructions}

  [1] Add now  -  I'll generate the token and copy it
  [2] Skip  -  I'll set it up later

  Select:
```

Expired / rejected token (401 / 403 mid-run)  -  the Expired-token decision from `$HOME/.claude/multi-agent-refs/keychain.md` Rule 1:
```
{Service} token expired (the service returned 401/403).
  Where to get a fresh one: {source URL/instructions}

  [1] Regenerate  -  replace {KEY_NAME} in place, then retry
  [2] Use a different token  -  map another Keychain entry, then retry
  [3] Skip and continue  -  drop this source (halts only if the token is required for the input)

  Select:
```

Render `question` + `label` + `description` in `outputLanguage`; `header` English. Names below are option semantics, not strings to print. The picked option is a choice, never the secret: the value enters via Step B clipboard.

- **Skip** (missing `[2]` / expired `[3]`) → skip semantics. During setup: `keychainMapping` stays `null`. During Phase 0 / mid-run: abort that service's contribution, warn and continue if non-critical, halt if critical (e.g. Jira token for Jira input).
- **Add now** / **Regenerate** → proceed to Step B (clipboard save). Regenerate reuses the same `{KEY_NAME}`.
- **Use a different token** → proceed to Step B, then re-run Step C identity binding for the new entry.

**Step B  -  Clipboard save** (token NEVER appears in terminal):

For PAT / API key / username:
```
  Copy the token to your clipboard, then press Enter.
  (Token will be read from clipboard and saved to Keychain automatically)

  Press Enter when ready...
```

Pipeline runs silently  -  value is piped via stdin (`-` sentinel) so it never lands on argv / shell history:
```bash
pbpaste | ~/.claude/lib/credential-store.sh set "<KEY_NAME>" -
pbcopy < /dev/null
```

(The shell driver auto-delegates to `~/.claude/scripts/keychain.py`, which writes both `-l` (label) and `-s` (service) attributes so callers using either convention find the same entry.)

For JSON file (Firebase)  -  same clipboard flow, JSON content never lands in argv or shell history:
```
  Open the Service Account JSON, copy its FULL contents to your clipboard,
  then press Enter.
  (Contents are saved to the Keychain exactly as issued)

  Press Enter when ready...
```

The pipeline then runs the same `pbpaste | ... set "<KEY_NAME>" -` and `pbcopy < /dev/null` as above. A key that arrives as a file (the App Store Connect `.p8`, the Google Play JSON) skips the clipboard: `set <key> - < <file>`.

**Firebase repeats per project.** Teams own several Firebase projects (legacy plus redesign, staging plus prod), each with its own key, and a crash URL from the second one used to fail the `project_id` check as if it were misconfigured. After each saved key, read `project_id` from the stored JSON (never ask) and offer another round: `Saved: <project_id>. Add another Firebase project? [y/N]`.

- Every key appends `{projectId, keychainKey, label?}` to `prefs.global.firebase.accounts`; the first one also fills `keychainMapping.firebase`, so a one-project setup is unchanged.
- Keys after the first are named `${USER}_Firebase_Access_Json_<projectId>` so they cannot collide.
- At run time `fetch-crashlytics.sh` picks the account matching the console URL's projectId, falling back to `keychainMapping.firebase`.

For GitHub (special case):
```
  ! gh auth login
```

**Step C  -  Identity binding** (after token saved):

```
  ✓ Saved to Keychain as <KEY_NAME>
  ✓ Clipboard cleared

  Which git identity uses this token?

    Existing identities:
      1. Ada Lovelace <ada@example.com>
      2. Ada Lovelace <ada@personal.com>
      n. Create new identity

    Select:
```

- Existing identity selected → add `{service}: <KEY_NAME>` to that identity's `servicePatMap`
- `n` (create new) → ask name + email → create identity → add to `prefs.global.identities[]` → map token
- First token ever (no identities exist) → skip picker, go straight to name + email
- `bitbucket_user` is excluded from identity binding (it's a username, not a PAT)

**Step D  -  Confirm + update**:

```
  ✓ Token mapped to identity: Ada Lovelace <ada@example.com>
```

Update `prefs.global.keychainMapping.{service}` with the key name.
Update `identity.servicePatMap.{service}` with the key name.

**Do not write `serviceStatus.{service}` here.** Saving a token is not evidence
that it works, and `ok: true` is read as evidence: `autopilot-arming.mjs`
refuses to arm on a recorded failure and treats an absent record as "not probed
yet", so a `true` written at save time is the one value that cannot be told
apart from a successful probe. A hosted service also has no host yet at this
point, so there is nothing to probe against. The probe belongs after Step 3.5,
where it is described.

**→ Next: if `{service}` is `jira` / `confluence` / `bitbucket` / `fortify` / `graylog` AND the corresponding
`prefs.global.hosts.{service}` is unset, run Step 3.5 (Host Prompt) inline before
the Auto-routing rule below. required  -  the pipeline cannot build API URLs without
the host. Firebase is exempt (see Step 3.5).**

**Auto-routing rule** (optional, on first token per platform):

If `platformIdentityRouting` has no rule for this platform yet, auto-suggest one:
```
  Auto-add routing rule?
    bitbucket.example.com/* → Ada Lovelace <ada@example.com>
    [enter=yes / n=skip]
```

This builds `platformIdentityRouting` incrementally  -  no separate Step 7 needed for most users.

## Step 3.5  -  Host Prompt (embedded in Token Save Flow)

**Not a standalone step**  -  runs inline at the end of the Token Save Flow whenever the saved token belongs to a **hosted service** (Jira, Confluence, Bitbucket, Fortify, Graylog) AND the host is not yet in `prefs.global.hosts`. Firebase tokens skip this step  -  Crashlytics is always on Google's fixed domains and `project_id` is embedded in the service-account JSON.

Right after Step D (identity mapping confirmed), ask:

```
Service host  -  needed to build API URLs for this token.

  {Service} host (e.g. jira.example.com): ___
```

Save to `prefs.global.hosts.{service}`.

**Then probe once, and record what it says.** With the token saved and the host
known, run `bash "$HOME/.claude/lib/credential-inventory.sh" --key {service}`
and write `serviceStatus.{service} = { ok: <probe result>, checkedAt: <now> }`,
with `error` on a failure. A probe that cannot run at all - no host for a hosted
service, no network - writes nothing, because "I did not check" and "I checked
and it worked" are different answers and only one of them is true. A failure is
reported in one line and does not undo the save: the token is stored, the person
is told it did not answer, and the Expired-token decision in
`$HOME/.claude/multi-agent-refs/keychain.md` is what they run next.

For Fortify, also ask `Fortify project version ids (optional, comma-separated - e.g. 1234,5678)` → `prefs.global.fortify.versionIds`. A ticket naming only an instance id carries no version, so the lookup silently no-ops without these; URL-referenced findings resolve either way.

For Jira, **discover the project keys instead of asking the user to recall them.** The token is already saved and the host is already known, so ask Jira which projects this person actually works in - a corporate instance has thousands of projects, and a typed key is a typo waiting to route branches and new issues at the wrong board:

```bash
printf 'Authorization: Bearer %s\n' "$TOKEN" | curl -s -H @- \
  "https://{JIRA_HOST}/rest/api/2/search?jql=assignee%3DcurrentUser()%20OR%20reporter%3DcurrentUser()%20ORDER%20BY%20updated%20DESC&fields=project&maxResults=100" \
  | jq -r '[.issues[].fields.project | "\(.key)\t\(.name)"] | unique | .[]'
```

Present the distinct keys, most-recently-worked first, as a picker; fall back to the free-text prompt `Default Jira project key (e.g. PROJ)` when the call fails or returns nothing (no VPN, fresh account). The picked key → `prefs.global.defaultJiraKey`. From the Jira host, derive `corpDomain` (`jira.example.com` → `example.com`) and pre-fill it so the Confluence / Bitbucket prompts only need the subdomain.

`defaultJiraKey` is a single global fallback, but one Jira host usually serves several repos with DIFFERENT keys, so the pass continues with a per-repo mapping. Show the repos, and let the key come from the discovered list rather than being typed again:

```
Per-repo Jira keys (optional)  -  repos whose project key differs from {defaultJiraKey}:

  [ ] 1. my-ios-app        (current: PROJA)
  [ ] 2. my-other-app      (current:  - )

  Toggle repos, then pick a project for each  -  discovered: PROJA, PROJB, PROJC. Enter to skip.
```

- The repo list comes from `prefs.projects` + `recentProjects` (when Step 5 already ran); a free-text repo path is accepted for repos not discovered yet, and a free-text key for a project the search did not surface.
- Each answer is PREPENDED to `prefs.projects[{slug}].jiraProjectKeys` (deduped, max 10 per schema). Example: `my-ios-app` → `PROJA`, `my-other-app` → `PROJB`  -  two repos on the same Jira host, two different project keys.
- Resolution order everywhere a Jira key is needed (placeholder replacement, branch names, new-issue creation): `prefs.projects[{slug}].jiraProjectKeys[0]` first, `global.defaultJiraKey` as fallback.
- **Re-run / update**: `/multi-agent:setup jira-keys` re-opens only this mapping without touching tokens or hosts.

Resulting shape:

```json
{
  "global": {
    "hosts": {
      "jira":       "jira.example.com",
      "confluence": "confluence.example.com",
      "bitbucket":  "bitbucket.example.com",
      "fortify":    "ssc.example.com",
      "graylog":    "graylog.example.com",
      "graylogTest": "graylog-test.example.com",
      "corpDomain": "example.com"
    },
    "defaultJiraKey": "PROJ"
  }
}
```

Placeholders `{JIRA_HOST}`, `{CONFLUENCE_HOST}`, `{BITBUCKET_HOST}`, `{FORTIFY_HOST}`, `{GRAYLOG_HOST}`, `{GRAYLOG_TEST_HOST}`, `{CORP_DOMAIN}`, `{JIRA_KEY}` in skills/commands are resolved from this block at runtime. If a host is ever missing when a phase needs it, Phase 0 prompts the same Host Prompt inline.

Graylog uses a **PAT** whose API auth is HTTP Basic with the token as username and the literal `token` as password  -  no separate username entry. It is optional by the null-mapping convention: `keychainMapping.graylog` or `hosts.graylog` left `null` degrades the log fetch to empty and never blocks a run.

Graylog is asked **twice**  -  test and production are separate instances, and a tester-minted trx id does not exist in production. After the production host:

```
Graylog test host (optional  -  Enter to skip): ___
Does the test instance use a different token? [y/N]
```

Test host → `hosts.graylogTest` (`{GRAYLOG_TEST_HOST}`); skipped means production-only search, which degrades nothing. Yes to the token question runs one more Token Save Flow pass for `graylog_test`; no (default) leaves it null and the fetcher reuses the production key. Run-time order is `--env auto`: production first, test on empty or unreachable, and the payload names which answered.

**Re-run / update**: `/multi-agent:setup hosts` re-opens the prompt to edit values without touching tokens.

Team-sharing note: Hosts are the only corporate metadata the pipeline needs. Tokens live in macOS Keychain (encrypted, never on disk inside the repo). Preferences file lives in `~/.claude/`  -  fully outside the repo clone. A teammate cloning the repo runs `/multi-agent:setup` once; host + token prompts run naturally together.

## Step 3.7  -  Repository read binding (embedded in Token Save Flow)

Runs inline when the saved token can read git repositories over https (a
GitHub PAT, a Bitbucket Data Center HTTP access token). The multi-agent-mcp
`repo_*` tools send a token only to a host bound to it here, and nothing else
in the pipeline writes this binding: a product map or a planner's request
naming a credential never creates one.

```
Repository hosts this token may be sent to for read-only clone and fetch
(comma-separated, empty for none). Suggested: {github.com | prefs.global.hosts.bitbucket}
  ___
```

Save the answer, lowercased, to `prefs.global.credentialHosts.{logical-key}`
(an array of hostnames). Empty leaves the key unbound. `/multi-agent:setup hosts`
re-opens it.

## Sequential onboarding loop (Step 3)

The Step 2 discovery summary is never the end of setup. Immediately after showing it, walk the missing services one by one in the fixed order the setup SKILL lists, and run the Token Save Flow for each.

- **One prompt per service.** Never collapse the list into a single "add missing tokens now?" yes/no, and never offer one multi-select covering all services: each service has its own source URL, key name, identity binding and host prompt, so each gets its own Token Save Flow pass.
- **Each service pass asks, in order: token, author, host, read binding (GitHub, Bitbucket; Step 3.7).** Step A/B collect the secret, Step C binds the git identity (author) - Bitbucket and GitHub included; every saved token gets an author - and Step 3.5 asks the host domain inline for hosted services (jira, confluence, bitbucket, fortify, graylog), plus the Fortify project versions and the optional Graylog test instance. GitHub and Figma skip the host question (fixed domains); `bitbucket_user` skips author binding (username, not a PAT). Never end a service pass with the token saved but the author or a required host unasked.
- **Skip is per-service.** A Skip answer leaves that service's `keychainMapping` at `null` and the loop continues with the next service. Skips never abort the loop.
- **`figma` and `figma_mcp` are distinct credentials for distinct tiers: ask both.** Skipping the PAT does not imply skipping MCP, and vice versa. The `figma_mcp` pass opens with a Remote / Local mode question instead of a clipboard paste (`setup/figma.md`): Remote generates a `figu_` OAuth token for the current user, Local wires the PAT-based local server. A claude.ai or remote Figma connector that already answers Figma calls is not an onboarded `figma_mcp`: the pass still runs while the key has no stored value.
- **`firebase` is two offers in one pass.** First the service-account JSON through Steps A/B (`setup/firebase.md` section 2), then the Firebase MCP registration (section 3), offered whether the JSON was saved or skipped. A `fetch-crashlytics.sh --probe` answer of `no-credential` means nothing is stored: it starts this pass and is never a reason to ask for a stack trace.
- The loop ends only when every missing service has been asked exactly once; then continue to Step 4 (Verify all).

Every token is optional in the sense that every service can be answered with Skip, but the asking is not optional. Phase 0 re-asks at runtime only for tokens the user skipped here.

## Identity learning (Step 3)

Each token save triggers an identity prompt:

```
Token saved. Which git identity uses this token?

  Existing identities:
    1. Ada Lovelace <ada@example.com>
    2. Ada Lovelace <ada@personal.com>
    n. Create new identity

  Select:
```

- First token ever → no existing identities → asks name + email → creates identity → maps token
- Subsequent tokens → pick existing or create new → maps token to that identity's `servicePatMap`
- Multiple accounts per platform supported (e.g. two GitHub tokens, each mapped to a different identity)
- Identity is stored in `prefs.global.identities[]`, token-to-identity binding in `identity.servicePatMap`

**Legacy compatibility**: If `prefs.global.gitIdentities` (deprecated) is present, `migrate-prefs.mjs` renames it to `identities` automatically.

## Inline Token Save Pattern

All tokens go through `~/.claude/lib/credential-store.sh` (Python helper and label/service attributes: `setup/SKILL.md` "Setup").

```bash
# PAT / API Key / JSON contents (from clipboard)
pbpaste | ~/.claude/lib/credential-store.sh set "<SERVICE_NAME>" -
pbcopy < /dev/null  # clear clipboard

# Non-secret value typed inline (a secret on argv is visible to ps and lands in shell history)
~/.claude/lib/credential-store.sh set "<SERVICE_NAME>" "<VALUE>"

# Key file from disk (the .p8, the Google Play JSON; or when the clipboard is unavailable)
~/.claude/lib/credential-store.sh set "<SERVICE_NAME>" - < /path/to/file.json

# Read  -  a JSON value comes back exactly as it was stored, newlines included
~/.claude/lib/credential-store.sh get "<SERVICE_NAME>"
```

For maximum stdin hygiene (the secret never lands on argv / shell history), use the Python helper directly with the `-` sentinel:

```bash
pbpaste | ~/.claude/scripts/keychain.py set "<SERVICE_NAME>" -
```

The shell driver auto-delegates `get`/`set`/`delete` to the deterministic Python helper at `$HOME/.claude/scripts/keychain.py` (Python 3 stdlib only, no external deps). The Python path writes both `-l` (label) and `-s` (service) attributes so items are findable regardless of how callers look them up. Set `KEYCHAIN_DELEGATE=0` to force the raw shell path.
