Provider Authoring¶
How to add a new AgentProvider adapter (Gemini, …) and prove it's done: implement the seam, then pass the two-tier conformance bar (issue #80 / ADR-0036). Two adapters ship today — claude-code and codex (internal/provider/claudecode/, internal/provider/codex/) — and both are working reference implementations of everything below.
Hard requirements — no escape hatch¶
- A durable, locatable transcript.
LocateTranscriptmust find a real file — verified available for Codex's rollout JSONLs and Gemini CLI's session recording. An adapter may not ship without one. - The lab-owned
.localcontext-file name.SeedMeta.ContextFileNameis a bare.local-suffixed name, never a repo-tracked one (issue #79 / ADR-0035). Making the CLI actually read it is the adapter's ownSeedWorkspacejob, live-verified — never solved by declaring a tracked name. - Live verification before merge. Tier 2 below is required, not optional, even though it never runs in CI.
- Core stays adapter-agnostic. No provider names or markers outside the adapter package — enforced by
internal/provider/neutrality_test.goandweb/src/providerNeutral.test.ts.
Author path¶
- Implement the seam in
internal/provider/<id>/— the fullAgentProviderinterface (internal/provider/provider.go). - Declare
SeedMeta(): context-file name (.local-suffixed), skills dir, exclude entries, andScrubPatterns/SeededPathPatternsin the BRE∩RE2 common dialect (issue #75 / ADR-0033). - Wire host config from the generic
-provider-bin/-provider-configmaps, with the adapter owning its own defaults (issue #78 / ADR-0034) — no provider-named field goes intointernal/config. - Add the one entry to the registration table in
internal/provider/conformance_test.go(TestConformance, packageprovider_test), constructing the adapter hermetically (temp dirs, a fake runner) with itsprovidertest.Fixture. Get Tier 1 green. - Run the Tier-2 live spikes below on a host with the real CLI (spikes 1–4 always; spike 5 where the adapter implements the override).
- Commit the compat record at
internal/compat/<providerID>/compat.md. - Verify core neutrality:
internal/provider/neutrality_test.goandweb/src/providerNeutral.test.tsmust both stay clean. - Register the provider in
cmd/lab/main.go.
Definition of done: Tier 1 green in CI, Tier 2 evidenced in the committed compat record (ADR-0036). Both shipped adapters passed this bar; internal/compat/codex/compat.md (issue #2 / ADR-0037) is the reference example of a compat record.
Beyond the required interface there are optional capability interfaces (internal/provider/provider.go): AuthPeeker, ConnectingReporter, DeepLinker, LiveSignals, LoginCodeReporter, RemoteCapable. Implement one only when the CLI genuinely supports the behavior — core detects each by type assertion and degrades gracefully when absent (ADR-0017).
AuthPeeker (LastAuthStatus(), issue #61 / ADR-0073). It feeds the agent-login line of a repo's readiness report, which is read with every repo list and every repo home and must start nothing. AuthStatus may run the CLI's status command — a process, and on a container-mode server a podman container (ADR-0057) — so readiness never calls it. LastAuthStatus returns the status the adapter's most recent completed AuthStatus check produced, whatever its age, with true; or the zero status with false when no check has completed since the process started. A check that failed (the status command missing, its output unreadable) or was cut off by its caller's context is not completed and never moves the peek: the logged-out stand-in AuthStatus returns for it is a spawn-safety default, not evidence of a logout, and publishing it would turn every repo's agent check red. The rule: it never runs the CLI, never touches the network or the filesystem, never refreshes the cache, and never blocks behind a check in flight — it reports the previous result until that check lands, and CheckedAt says how old it is. Both shipped adapters implement it the same way: the refresh path stores the status of each completed check (no error, the caller's context still live) into an atomic.Pointer[provider.AuthStatus] while it holds the auth mutex, and LastAuthStatus loads that pointer without taking the mutex, because the mutex is held for the whole status command. The providertest fake mirrors that: it reports the status its last AuthStatus call returned, not its live scripted state, and the peek is not counted as a check. Without the capability, the agent-login check is simply left out of the report.
Conversational state (ReadChat, LiveSignals, Chat.StateDetail, ADR-0038 / ADR-0078). The adapter owns "what state is my agent in"; core only forwards it and applies the ended-run override. ReadChat receives a provider.ReadSpec: besides RunID, RuntimeDir and TranscriptPath, it carries Home (the run's private instance HOME) and Worktree (the run's worktree path, the one cwd unique to the session). Core fills RuntimeDir and Home only for an active run and leaves both "" for an ended one, so a terminal read never consults live signals. Both are opaque locations: use them to read whatever state your CLI keeps itself, and ignore them if it keeps none (codex). Claude Code composes its state from the CLI's own session-registry status (under Home, matched by Worktree) layered over the transcript fold; that precedence is the worked example (internal/provider/claudecode/chat.go, ADR-0078). Rules for an adapter that does this:
- Prefer the CLI's own status over a guess from the transcript tail, and never map an "idle" status straight to needs-input: idle cannot tell a turn that just ended from a fresh session, so let the transcript decide that case.
- An unusable status (entry missing, empty or unknown value) must fall back to the transcript alone, never to an error.
- Set
Chat.StateDetailto the CLI's human reason when it gives one (Claude:waitingFor, "permission prompt"). It is free text for display, forwarded verbatim to the status line, state dot and needs-input push; core never branches on it, soStatestays the contract. - If
LocateTranscriptcan name a new conversation before its file exists (Claude after/clear), an active read of that missing file must be an idle empty chat, notErrTranscriptGone; an ended read of a missing file is stillErrTranscriptGone. LiveSignals.SpoolSig(runID, dir, home)is the cheap change digest the tailer compares so it republishes while the transcript is byte-frozen. Digest everythingReadChatreads outside the transcript, the spool underdirand the state registry underhome; an emptydirorhomeskips that half.LiveSignals.Setuparms only what you need for dialog capture. Claude's per-run settings file carries the PreToolUse/PostToolUse dialog hooks andenvand nothing else; there is no Notification hook, because itsidle_promptfires after every turn even while background agents run.
Transcript retention (RetainTranscript, issue #81). Every teardown wipes the run's private HOME, and your transcript lives in it. Just before the wipe, core calls RetainTranscript(ctx, worktree, home, transcriptPath, destDir) with the run's stored transcript path and an empty, core-created destDir (<state>/transcripts/<runID>/). Move into destDir whatever an ended ReadChat needs, and return the path core should store; core later reads it with an ended spec (no Home, no RuntimeDir). For a single-file transcript the whole implementation is one call:
func (p *Provider) RetainTranscript(ctx context.Context, _, home, transcriptPath, destDir string) (string, error) {
if err := ctx.Err(); err != nil {
return "", err
}
return provider.RetainFile(home, transcriptPath, destDir, p.rename) // p.rename nil → os.Rename
}
provider.RetainFile renames on the same filesystem and copies (0600, fsynced, then removes the source) on a cross-device EXDEV. It returns ("", nil) for an empty or missing source and refuses anything outside home (including through a symlinked parent), any symlink or non-regular file, and any existing destination. Keep the file byte-for-byte: no rewriting, no lab-owned format (ADR-0016). Only the current transcript is retained; earlier /clear segments are not. Never touch destDir's siblings. If your ReadChat also reads files beside the transcript, move those too. Claude Code's ReadChat doesn't, so it leaves its <sessionId>/ sidecar dir behind; Codex moves its rollout without the date dirs. Keep the rename function in an unexported field so your tests can return an EXDEV *os.LinkError and exercise the copy path.
"Chat about this" (DialogAnswer.Chat / QuestionAnswer.Chat, issue #58). AnswerDialog carries one more answer shape: the operator chose to talk about a question instead of answering it. It carries no text. The agent is expected to ask what the operator wants to know, and the operator answers through Reply once the dialog is gone. On a single-question dialog Chat is set on the DialogAnswer and every answer field is empty. On a multi-question dialog Answers holds the operator's answers to the questions before the chat, in order, and ends with one entry whose Chat is set. An adapter with answerable question dialogs must reproduce exactly that path on its own dialog — enter the earlier answers as given, then make the "chat about this" choice on the question it was made on — inside the one AnswerDialog call, so the caller's per-session lock covers it. Validate before any key plays: a non-question dialog is ErrDialogNotAnswerable; a chat entry combined with an option, followed by another entry, or preceded by an invalid answer is ErrInvalidReply. Render a dialog set aside this way through its dismissed outcome, never as a mismatch — but if the adapter drives the dialog blind, do flag a recorded answer the operator never gave. An adapter without answerable dialogs (codex today) simply keeps returning ErrDialogNotAnswerable — the UI offers the action only on an answerable question dialog, so it never appears there. Claude Code's implementation and its live-verification status are in internal/compat/compat.md §7 ("Chat about this").
Tier 1 — the conformance suite (CI, every adapter)¶
Entry point: providertest.Conformance(t *testing.T, p provider.AgentProvider, fx providertest.Fixture) (internal/provider/providertest/conformance.go). Fixture.AttributionSamples (required, ≥1) are real single-line marker strings the CLI writes into commits/PRs — your adapter's ground-truth test vectors; Fixture.CleanSamples (optional) must NOT match, guarding against an over-broad pattern. Fixture.SeedTranscript (required, issue #81) writes one minimal native session for a worktree under a given HOME (plus whatever registry your LocateTranscript keys on), so that the locate hits and an ended ReadChat yields at least one message. The suite drives the retain round-trip through it and never learns your layout.
Subtests assert:
- patterns-dialect —
ScrubPatterns/SeededPathPatternscompile viaprovider.CompileScrubPatterns(issue #75 / ADR-0033);ScrubPatternsnon-empty. - context-file-lab-owned —
ContextFileNameis a bare.local-suffixed name (issue #79 / ADR-0035). - seedmeta-clone —
SeedMeta/Models/Efforts/SpawnOptionsreturn defensively-cloned slices. - catalogs — model/effort catalogs are non-empty with unique non-empty values; spawn-option specs are typed with valid defaults.
- spawn-argv —
argv(prompt) == argv(no prompt) + [prompt]; every declared spawn option round-trips. - spawn-remote — a
RemoteCapableadapter's argv differs between remote on/off exactly as its interface declares; a non-RemoteCapableadapter produces an IDENTICAL argv for both values (no undeclared coupling). - auth-flow —
AuthFlow().Kindis a recognizedAuthFlow*constant. - login-session — the id charset and
tmuxx.IsLoginSession(tmuxx.LoginSessionName(ID()))hold (issue #77 / ADR-0034). - read-chat —
ReadChaton a fresh spawn (empty transcript path, runtime dir absent or empty) yields an idle read, never an error; a transcript path that no longer exists, read as an ended run (no runtime dir, no home), surfacesprovider.ErrTranscriptGone, not a raw error. An active read of a missing file is not pinned. - locate-homeless —
LocateTranscriptwith no per-run instance HOME is a miss ("", nil) — never an error, never a fall back to the machine's master store (issue #202). - retain-transcript — the round-trip: seed via
Fixture.SeedTranscript, then locate, read as an ended run,RetainTranscriptinto an emptydestDir,RemoveAllthe HOME, and read the retained path as an ended run. That read must return the same messages and cursor as the first one, and the retained path must lie underdestDir. A sibling ofdestDirstays untouched. An empty or vanished transcript path returns("", nil)and leavesdestDirempty (issue #81). - inject-credentials — with no master credential present,
InjectCredentialsreturns nil and writes nothing to the master store; the injector only ever copies FROM the master, never into it. - credential-authority — the credential-authority obligations (
CredentialsSig,AdoptCredentials, …;internal/provider/provider.go) hold against a genuinely absent master store.RefreshCredentialsshells out to the live CLI, so it's pinned in adapter-side unit tests, not here. So is the logged-out rule (issue #101): a credential file that exists but holds no usable tokens — unparseable, or with its tokens emptied the way claude clears them after a failed refresh — must read as""fromCredentialsSigand be refused byAdoptCredentialswith an error wrappingprovider.ErrCredentialsLoggedOut, both decided by one shared adapter-side check. Otherwise lab adopts a dead file into the master store and fans it out to every live run. - master-store-spec —
MasterStoreSpecreturns a non-empty absoluteHostDir, resolved freshly per call and honoring its declaredEnvVaroverride (issue #211). - seeding-exclude-coverage — in a real temp linked worktree, the provider's
SeedWorkspaceplus the realinternal/seederrun, in production order, leavegit status --porcelainempty; the context file/skills dir exist; every seeded path matches aSeededPathPattern. - seeding-incogni — same, with
SeedOpts{Incogni: true}: no tracked-file writes. - seed-home-containment — seeding against a temp instance Home leaves the machine's master store untouched: HOME-global trust grants (claude's
~/.claude.json, codex'sconfig.toml+AGENTS.md) land under the run's private Home. - scrub-markers — every
AttributionSampleis stripped by the adapter's ownScrubPatternsthrough both real engines (RE2 viaprovider.CompileScrubPatterns, POSIX BRE via a realgrep -i, skipped when absent) and byprovider.NewRegistry(p).ScrubRegexps()— the union path the agent-API sanitizer actually runs (ADR-0033).
A deliberately-broken fake adapter lives in the suite's own tests; failures name the obligation they broke.
Tier 2 — live spikes (required, documented, not CI-run)¶
Held to the ADR-0008 live-verification bar: real CLI, real host, no credentials in CI. Evidenced by the committed compat record, not by a test that runs on every push.
- transcript — locate by cwd, read/map to the universal schema, confirm a NEW transcript identity on context clear (native rotation or a synthesized epoch — see
LocateTranscript's doc); and confirm when the transcript is born — at session init, or lazily at the first turn (an idle interactive session may then have no transcript file at all, so nothing may gate first-message delivery on its existence — codex 0.133.0 is the precedent, issue #96). - reply / dialog-answer / interrupt — hazard-check the send-keys recipes against the real TUI; double-Esc/Ctrl-C must never be able to kill the session.
- context-file discovery — prove the CLI actually READS the lab-owned context file (e.g. Codex ↔
AGENTS.local.mdvia project config). - incogni attribution ground truth — capture what the CLI actually writes into commits/PRs and reconcile it against the adapter's
ScrubPatterns; these live samples becomeFixture.AttributionSamples. - dialog auto-dismiss defeat — conditional: only for adapters that override their CLI's unattended dialog timeout (claude:
CLAUDE_AFK_TIMEOUT_MSvia the per-run settingsenvblock, compat §11; codex has no equivalent knob today). Live-verify the override actually reaches the dialog timer — a small value self-resolves an undriven dialog early — AND that the effectively-never max holds: the dialog survives well past the CLI's default, with no immediate-fire hazard at the cap.
Compat record convention¶
Follow claude-code's worked example, internal/compat/compat.md: numbered sections, each carrying a provenance tag (live / fixture / schema extraction); captured fixtures under testdata/ tagged with the CLI version (e.g. -2.1.198); opt-in live tests gated by LAB_COMPAT_LIVE=1 (internal/compat/live_recipes_test.go, no build tags). A new adapter's record lives at internal/compat/<providerID>/compat.md, same shape; claude-code's stays where it is.