# Connect GitHub: implementation plan, 2026-11-23

Plan branch: `github/connect`, updated against main `33fd8660`, which includes
`github/egress-check`. Main is merged without rewriting the published plan.
This branch changes documentation only: this plan, its reviewed copy list and
the probe evidence. The controller requested the revised plan before code.
The full Fable review and the controller's 2026-11-23 rulings are incorporated
below; the rulings supersede the earlier plan's narrower assumptions.

Authority: the [approved spec](../specs/2026-11-22-equipo-github-connector.md),
G1 to G4, G9 and G10, and the controller's 2026-11-23 step-4 brief. The landed
Projects and card-name corrections remain authoritative: an omitted
`remember_name` skips learning, only an explicit person answer learns, private
names do not override one unique trusted match, and repository text does not
become trusted by saving an unchanged form.

## Entry gate and boundaries

CARLOS egress passed on 2026-11-23 at about 19:12 UTC. The controller ran the
same unauthenticated request from a temporary CARLOS app with Equipo's default
capabilities on the bds fleet, Dublin host annie-welding: status 200, 38ms and
11ms, TLS peer 4.208.26.200:443. The app was deleted. The
[probe record](../specs/2026-11-22-equipo-github-connector-probe.md) records the
method and control. This meets the implementation entry gate. Running the
landed `check-github` on production after its next upgrade remains a
confirmation, not a claim that this diagnostic has already run there.

Deliver only connection, repository discovery and reading. No GitHub push,
repository creation, proposal, pull request, hosted-check decision or merge;
no write token. The App requests the approved G4 installation permissions
once, but project tokens in this phase request only contents/read and
metadata/read. Inventory tokens request metadata/read only. Pull request,
checks, status and Actions permissions on tokens wait for step 5.
Future publication and merge will use a separate purpose and lease-bound
sealed write token, never a cached read grant widened in place.

All branches start from the preceding reviewed and landed main, not from an
unreviewed stack. The controller assigns review and lands each one. No merge
or deployment by the implementing agent. No real probe credentials or files
under `~/private_keys` are read; tests generate their own keys.

## Reviewable branches

| Branch | Reviewable result | Principal test boundary |
| --- | --- | --- |
| `github/connect-app` | Owner creates a private App, verifies its installation, confirms Connect and can Disconnect on the web. | Manifest/state, current owner, sealing, audit and lifecycle tests against `forgetest.GitHub`. |
| `github/connect-repositories` | GitHub appears in Projects and Available to add, including when the runner is offline. Owners add projects; disconnected projects stay visible. | Complete inventory snapshots, stable repository IDs, resolver and device API tests. |
| `github/connect-read` | A current primary runner can clone, fetch, index and answer about an active GitHub project with a sealed, single-repository read token. | New protocol, broker authority, token isolation, actual git reads and cancellation tests. |
| Native follow-up, branch named by controller | iPhone and Mac show connection state and open web setup. | Existing ProjectList fixtures plus native state, link and permission tests. |

A and B ship behind `EQUIPO_GITHUB=1`, default off. The flag gates the owner
section, setup routes, inventory refresh, Projects additions and the C read
broker. The refusal of GitHub tasks never depends on this flag. Staging may
enable it; production stays off until C and the live read run pass. Test default-off and enabled states, including direct requests.
The first two branches add no runner wire fields. They use the existing
ProjectConnection, ReachableProject, Project and CardLink fields. GitHub
execution stays refused until C supplies the complete guarded read path.

Step 4 allows only Coordinator search, read_file and answers on GitHub.
Every task on a GitHub project is refused at recording, before dispatch,
including moving an existing task onto a GitHub project. This covers
Engineering, Checks, Copy, Merge and every worker, even with the instance flag
off. Return a tool result, not a frame error. Apply the same admission guard
to web/device task writes, moves and retries, with a defensive dispatch check.
Tests attempt every specialist and worker separately, move an existing hub
task to GitHub, and try recording/moving with the flag off. Assert the refusal
text, unchanged source task on a refused move, and no queued or sent work.
Remove each guard, including the flag-off task and read guards, and require a
failing test. Turning the flag off after data exists refuses reads with
`github.read_unavailable`; it never enables tasks. Hub behavior
stays unchanged. Luna-reviewed copy: `github.read_only`: "Equipo can read this
GitHub project, but cannot change it yet."

## A. App connection

1. Write lifecycle and HTTP tests first. Add a small instance-only GitHub
   client under `internal/equipo/github` and the generated-key fake described
   below. Pin `api.github.com`, HTTPS, the probed API version `2022-11-28`,
   explicit Accept/User-Agent headers, bounded response bodies, timeouts and
   refused redirects. Construct paths from validated IDs; never follow URLs
   returned in GitHub JSON. Map errors to bounded typed outcomes, without raw
   bodies, URLs containing conversion codes, headers or credentials in logs.
   Ship shape redaction and secret-scan coverage in A, before any App secret
   is handled: ghs_, ghu_, gho_, ghr_ and PEM private-key headers/blocks, as
   detailed in C. Generated samples and an empty known-secret list must still
   be protected. Remove each pattern individually to kill its regression.
2. Add team records for forge connection attempts and forge connections in
   additive migrations. Include them in Models and Schema, not BootSchema. Store App
   ID, account numeric ID/type/login, installation ID, lifecycle state and a
   monotonic generation. Enforce one active private App per team/account with
   a database uniqueness guard, including concurrent Connect attempts. Keep
   secrets out of all public models. Use the next
   free migration numbers on landed main; leave 0100 and 0101 unchanged.
3. Add an owner-only GitHub section in Settings, separate from model
   connections (`connectionRecord`). Use distinct forge-connection model and
   store names. Proposed action paths are `/github/connect/start`,
   `/github/connect/manifest`, `/github/connect/installation`,
   `/github/connect/check`, `/github/connect/confirm` and
   `/github/connect/disconnect`. Start, Check again, Connect and Disconnect
   are CSRF-protected POSTs. Any current owner may Check again, Connect,
   supersede a pending setup or Disconnect; none requires the starting owner.
   Check the current roster in each write transaction. Only the two callbacks
   remain bound to the initiating owner and session. Callback GETs use state.
   Starting again for a pending setup deletes its key in the same transaction
   that starts its replacement. Audit both cancellation and creation, show
   `github.app_remains` plus the old App cleanup link, and invalidate both old
   callback states. Test a different owner superseding the first owner's
   attempt, including a concurrent late conversion. Starting for an already
   connected account returns `github.already_connected` with the verified
   login; it does not create another App.
   The start form identifies the intended account and its type; the manifest
   posts to GitHub's personal or organisation registration page. Only this
   page extends Rastrillo's `form-action 'self'` to
   `form-action 'self' https://github.com`; preserve every other directive.
   Test the response header and a browser-lane form POST plus redirect chain
   back to the clean same-origin page. Route GitHub to the controlled browser
   fixture without changing the tested origin policy. Assert another Settings
   page cannot submit externally. Remove the exception to kill the browser
   test; applying it globally must kill the unrelated-page header test.
4. Generate unpredictable state, store its digest, bind it to the verified
   owner, browser session, instance origin, intended account and attempt.
   Use one absolute ten-minute deadline for both redirects. Atomically consume
   the first stage before conversion; issue a different single-use state for
   installation without extending that deadline. Reject wrong-stage, wrong-
   session, expired, replayed and concurrent callbacks. A session losing its
   owner role cannot finish an attempt. A failed or uncertain one-use
   conversion requires a fresh attempt, never guessed recovery with the code.
   Claim state consumption in a primary-database transaction, never on a
   replica or in a process-local lock. Concurrent callbacks on two instance
   processes must convert only once. Redirect both callbacks immediately to a
   clean same-origin status URL without code or state, including failures;
   disable caching and referrer propagation on callback responses.
   A manifest-stage callback after ten minutes never converts the code and
   therefore has no key: show `github.setup_failed` plus `github.app_remains`
   and its cleanup link, not Check again. Only installation-stage expiry with
   a held key uses `github.redirect_expired` and offers Check again. Test both
   stages with an injected clock and assert the exact keys and conversion
   count. After the pending key's own 24-hour expiry, use pending-expired
   wording instead, with no Check again action.
5. Manifest: private App, no webhook events, no OAuth-on-install, exact G4
   permissions, instance-owned redirect/setup URLs. Convert the code once.
   Keep only the private key and required public identifiers. Discard webhook
   and client secrets immediately. Validate the App with its own short-lived
   RS256 JWT. Derive a dedicated purpose key from EQUIPO_INSTANCE_KEY using
   kernel.PurposeKey; seal the PEM with AEAD and bind ciphertext to the
   instance, connection and App ID. Do not reuse a model-credential domain.
   An unreadable sealed key yields typed `reconnect`, with no fallback key,
   raw decrypt error or retry loop. Test a changed instance key and corrupt
   ciphertext. Preserve public identity so the owner can clean up the old App.
6. Read `/app/installations` and the selected installation using the App JWT.
   Match the verified App/account numeric identity, exact permissions and
   absence of suspension. For a previously connected App later uninstalled,
   keep its key for seven days from the first verified uninstall observation.
   While held, any current owner's Check again or the next refresh while in
   use can discover a reinstall using the JWT. If the same App/account ID and
   approved permissions match and it is not suspended, restore the connection
   without a new Connect tap. At seven days delete the key, show
   `github.app_remains` and its cleanup link, and require a fresh App to
   reconnect. Test reinstall inside the window and expiry outside it, including
   account mismatch, unchanged first-seen deadline across refreshes, and races
   at the boundary. This seven-day rule is separate from the 24-hour lifetime
   of a created-but-never-connected App. Accept both selected-repository and
   all-repositories installations, including a later admin switch between them. GitHub's admin
   choice plus the owner's Connect sets authority; display GitHub's actual
   reachable list. The redirect's ID is a hint, never authority.
   Pending org approval stays pending within a separate 24-hour key lifetime
   starting at successful conversion. The ten-minute deadline binds only the
   two redirects, not Check again or Connect. Within 24 hours, an owner can
   use Check again to read the installations with the App JWT, without a new
   redirect. Read the complete repository count, show the verified account
   and count, and require explicit Connect before making it live.
7. Recheck the roster, the deadline appropriate to the action, and generation
   in every write transaction. Use the transaction handle and explicit allowed fields.
   Append each lifecycle write's audit event in that transaction, including
   Check again, expiry and availability changes as well as Connect/Disconnect;
   an audit failure rolls back its write. Network requests run outside write
   transactions, with current authority rechecked before committing results.
   Concurrent Disconnect or owner removal wins over late conversion/list/mint
   results. At 24 hours for an unconnected App, failed conversion or
   Disconnect, or seven days after a verified uninstall without reinstall,
   delete key material and invalidate pending grants. Expiry runs through the
   trusted maintenance path with the same roster and lifecycle checks; interactive writes recheck
   expiry even if maintenance has not run. Disconnect deletes the sealed key,
   increments generation and prevents new minting in that transaction. Keep
   public identity and projects for the disconnected display. Explain that
   the App still exists on GitHub and link its settings for deletion. Use the
   verified App slug for its settings URL, or the intended account's Apps
   settings list if conversion never established a slug. Do not claim to have
   uninstalled it. Reconnect uses a fresh random App-name suffix and verifies
   the account again. A new installation revives existing projects only by
   matching account ID and repository ID, never login/name alone.

The count/list API needs an installation token. Use a separate instance-only
inventory token with metadata read and no content or other permissions,
covering the installation's GitHub-authorised repositories. It never goes to a
runner and never becomes a project read token. Test conditional requests with
fresh tokens against the controlled live connection. If token changes prevent
304s, retain this metadata-only token in instance memory until shortly before
its one-hour expiry; never persist it. Revoke/drop it on invalidation. Cache
ETags per installation, generation and page, not across scope changes.
Omitting the permissions object would inherit writes, so tests must forbid
that. This narrow metadata credential is necessary for the inventory endpoint,
not an exception to one-repository runner tokens. Verify its actual permission
shape against the fake and the controlled live connection before landing A.

## B. Reachable repositories and Projects

1. Add a reachable-repository table keyed by connection and GitHub numeric
   repository ID, and a project binding table retaining that ID. Store the
   canonical GitHub spelling, description, default branch, visibility,
   archived flag and last push. Preserve project ID, stars, task history,
   owner title/description and names through a rename or transfer. A transfer
   is reachable only if the verified destination installation includes it;
   never infer access from the old name or follow a redirect with credentials.
2. Refresh in the instance every 55 seconds while the connection's Projects
   list or work is in use, hourly otherwise. Define in-use from recent
   authenticated views and active GitHub work, using an injected clock and
   coalesced refresh. Claim a bounded refresh lease in the primary database
   with current roster/generation checks, so two processes cannot refresh the
   same connection concurrently. Test takeover of an expired claim and refusal
   of stale completions. Support ETags, 100 items per page, and at most 1000
   repositories per installation. A total above that limit, or a 1001st row,
   makes the new snapshot unknown, never empty or partially published. Keep
   any prior snapshot labelled stale without granting new authority. Show
   `github.too_many` beside `github.choose_repositories`; its %s is the bound
   formatted with Rastrillo's locale number formatter, never a hard-coded
   "1,000". Test a fake listing 1001, including misleading count metadata,
   and a locale with different grouping. Allow a bounded overflow probe if the
   total is unreliable, to detect the 1001st row without publishing it; do not
   keep paginating after overflow. Publish only complete snapshots. Do not
   remove repositories because one page failed, or show an unknown count as zero. Rate limiting
   and network failure retain labelled stale data but confer no new authority.
   Classify both 429 and GitHub's 403 rate-limit form (rate-limit headers,
   Retry-After and bounded structured classification) as retryable/stale,
   never lost access. Distinguish ordinary forbidden, revoked and suspended
   outcomes. A generic 403 does not by itself prove uninstall or deselection.
   Reconcile all pages after changes so a changed later page cannot hide behind
   a first-page 304. Never follow an off-host pagination link.
3. Join this instance inventory with the existing hub inventory from the
   person's primary runner hello. GitHub discovery works with that runner
   offline. Never import GitHub reach from hello.repos or hello.catalog:
   filter both to hub entries before joining the instance's GitHub snapshot.
   Mutate both filters and prove a forged hello cannot add or revive reach.
   ProjectConnection uses `forge: github`, a stable connection ID,
   account-labelled title and current state. Available rows use existing
   `connection_id`, `forge`, `repo`, `title`, `description` and source fields.
   Existing hub IDs, values and allowed-list compatibility remain unchanged.
4. Owner add checks current roster, connection generation and repository ID in
   its transaction and appends its audit row there. Add grants no wider reach.
   An ordinary member's tool refusal is a result, never a frame error that
   revokes their runner. Disconnect, uninstall, suspension and deselection
   preserve projects but mark the connection/project unavailable and remove
   add authority. Unknown availability is distinct from disconnection.
5. Reuse the exact code resolver, trusted-name precedence, bounded placement
   cards, personal-name confirmation and turn project block across both
   forges. GitHub descriptions remain bounded, redacted, labelled repository
   data, never trusted naming instructions. A miss for an explicit canonical
   github.com/owner/repo key, or a selected project bound to GitHub, produces
   the GitHub card: use Choose repositories on GitHub when a verified
   installation exists, otherwise the not-connected notice and web setup link.
   A hub key, including the historical bare owner/repo shorthand, follows the
   existing hub access request. An unresolved human name goes to placement;
   it does not guess a forge or issue an access request. Derive settings links
   from validated account/type/ID, never model text. Members can see the link;
   GitHub decides who may change the installation. A selection becoming
   unavailable must not poison queued turns or lose another turn's reply.
6. Update `docs/api/equipo-v1.md`, OpenAPI descriptions/examples and native
   fixtures for the existing `GET /api/v1/projects` response and add route.
   Keep DELETE `/projects/{id}/names`, per-viewer same-revision private-name
   events and existing star behavior. No new device write route is needed:
   connection setup stays on the web. If implementation requires an extra
   device field or route, add its schema and contract tests in the protocol
   branch before using it, not as an undocumented side effect here.

## C. Read broker, protocol and runner

1. Start with wire and mixed-version tests. Main currently speaks protocol 28;
   allocate the next free number at implementation, named ProtocolGitHubRead.
   Old runners continue hub work but never receive GitHub dispatches, catalog
   additions or new frame types. A person asking to read on an old runner gets
   the reviewed update notice. Test rejection at dispatch, token request and
   encode/decode boundaries, not just a UI predicate. Reject unsupported
   GitHub writes even on the new protocol.
2. Introduce typed `forge_catalog`, `forge_read` and `forge_read_result` frames.
   Catalog data contains only active project IDs, validated repository keys
   and numeric IDs, connection IDs/generations and availability. It contains
   no token and no non-project repository for cloning. A read request carries
   an unpredictable request ID, expected project/connection/generation and
   purpose (index or Coordinator read), plus the current turn for a
   Coordinator read. There is no step-read purpose in this phase. The server
   resolves identity and authority itself. Catalog invalidations carry enough
   stable identity and generation to delete stale local data; a complete
   reconnect snapshot also removes projects absent from it.
3. The read result carries that request binding, a typed refusal or a sealed
   credential, and expiry. Bind ciphertext to the recipient's enrolled seal
   key, connection generation, project/repository ID and key, purpose, request
   ID and turn where applicable. Use a short delivery deadline
   separately from the token's one-hour expiry. Add typed sealbox helpers for
   this purpose, preserving model-credential formats. Reject stale, replayed,
   cross-runner, cross-repository, cross-generation and altered envelopes.
   Results of refusals still complete the request; no hanging tool call.
4. Broker authority requires EQUIPO_GITHUB=1, a current team member, their
   current primary runner, a live connection, active project, reachable numeric repository ID
   and applicable current turn. Keep existing execution gates: an active team
   owner must exist; the reading requester may be an ordinary member. Every
   current member's primary runner may read connected GitHub projects, unlike
   the hub's per-agent reach. Authorize each turn before any local clone/index
   read, including search_code and read_file when no network fetch is needed.
   Mint with exactly one `repository_ids` entry and explicit contents/read
   and metadata/read only. Validate returned
   scope and expiry before sealing. No broad or write-capable fallback after
   a GitHub rejection. Recheck authority after minting; revoke and discard a
   token if Disconnect, runner replacement or roster removal won the race.
5. Keep the runner's token only in private process memory until shortly before
   expiry, keyed by the full binding. Reuse only after fresh server
   authorization of the turn and each network operation/generation. Inability
   to contact the instance denies reading, including cached local content.
   Keep an opaque grant ID, never send the token back in a request. On refused
   authorization or invalidation, cancel reads, revoke/drop the token and
   delete the clone and index entries under the same per-project exclusion
   used by reads. Fence late fetch/index results so they cannot republish
   deleted data. Apply the lifecycle table below, also after reconnect/restart.
   Deleting the sealed App key stops minting but does not erase issued tokens:
   the instance holds transient decrypted PEM/JWT during active API calls and
   the cached metadata token; the recipient runner holds its project token.
   Cancel outstanding calls and drop instance plaintext references at deletion.
   The runner revokes its own held token and drops it on notice/refusal; the
   instance revokes its metadata token. Best-effort revocation never delays
   local denial. Go heap erasure is not guaranteed. A compromised runner can
   retain a read token for up to one hour, as the spec accepts, and can keep
   content it already copied. Honest-runner deletion does not undo disclosure.
6. Add a read-only GitHub Forge behind NewForges. Remote(Read) obtains the
   broker grant and returns a canonical HTTPS URL with username
   `x-access-token`; Remote(Push), Create, Propose and Merge refuse locally
   without a network call. Keep the hub's Agent/CreateIn identity and behavior.
   Git receives credentials only via the existing environment header path,
   with redirects refused and URL/config rewrites guarded. Redact raw and
   encoded Basic credentials, including the username, before any git failure
   leaves the process. Reuse the A shape redactor in runnerproto/event_io.go
   and secret-scan fixtures for ghs_, ghu_, gho_, ghr_ and PEM private-key
   headers/blocks (including truncated blocks), alongside existing patterns.
   Test without a known-secret list and kill each removed pattern. Exercise
   the pinned gitleaks scan with generated shape samples too; if a pattern is
   missing, add an explicit trusted rule rather than weakening scan policy.
   No token in argv, disk, repository config, sandbox,
   Mac worker request, prompt or report.
7. Index only active reachable GitHub projects. Exercise actual clone, fetch,
   default-branch discovery and bounded read/index against a local Git HTTP
   fixture; a Coordinator then answers about the fetched content. Inventory
   text and repository content retain the current injection defenses. Tests
   cover expiry refresh, deselection, disconnect during clone, primary runner
   replacement, missing connection, and two forges with the same basename.

## Local data lifecycle and read guards

On a live socket, send an invalidation as soon as the instance commits the
change. A disconnected runner applies the complete catalog on reconnect; a
runner missing that notice must delete on its next refused read authorization.
Index scheduling also needs current authority, even without a person turn.
No local read may bypass authorization because a directory already exists.
Tests start with both a populated clone and published index, then assert both
are absent and no stale result is returned. Test notification and missed-notice
paths separately, including failure to delete: deny reads until cleanup works.

| Change | Instance decision | Honest runner action |
| --- | --- | --- |
| Disconnect | Delete sealed key, bump generation, invalidate all grants in the write transaction. | Cancel reads, revoke/drop held tokens, delete every affected clone and index entry on notice or next refusal. |
| Uninstall | Verified loss makes it unavailable and starts a seven-day key-retention deadline. JWT Check again or in-use refresh discovers a same-App/account reinstall and revives without another Connect. At seven days delete the key and require a fresh App. | Delete all affected clones/index entries when told or refused; re-clone only after verified reinstall and new authorization. |
| Suspension | Verified suspension denies authorization while retaining project identity for recovery. | Delete clones and index entries; re-clone only after verified recovery and a new grant. |
| Repository deselection | A complete inventory or authoritative scope refusal removes reach for that numeric ID. | Delete that repository's clone/index and token; other reachable projects are unchanged. |
| Rename or transfer | Preserve project identity, invalidate the old key/binding, and verify the new account installation and repository ID. | Delete the old path and index entry, then re-clone under the new canonical key only with fresh authorization. Never follow a credentialled redirect. |
| Project removal | Invalidate its grants even if the repository remains in Available to add. | Delete its clone/index; do not index non-project inventory rows. |

After reconnect, revive projects by the verified account ID plus repository
ID. A renamed account or repository can match; reuse of an old name with new
IDs cannot. A transfer to another account needs that account's verified
connection and reach. The old binding alone grants nothing.

Source locations below are against main `33fd8660`. The shared fetch
validator is widened; DefaultBranch gets explicit read-key validation, and
Heads gets a hub-only guard. Caller authority is tightened separately. The
closed forgekey host list, router no-fallback behavior and hub identity stay intact.

| Guard / path | Step-4 treatment |
| --- | --- |
| `thin/forge.go:414`, Clones.fetch used by Ensure/Shallow | Replace ValidHub with closed-host Parse and a current GitHub read grant; hub reads retain their existing checks. |
| `thin/index.go:578,613,691`, SearchCode/ReadFile/ready | Add per-turn authorization before local content, including the existing-directory fast path; index refresh has an index-purpose grant. |
| `thin/forge.go:631`, Clones.DefaultBranch | Add a closed-host Parse guard and require a current GitHub read grant before ls-remote; permit it for indexing. Mutate the guard and read authority independently; use a permissive forge spy to prove invalid keys never reach the adapter. |
| `thin/merge.go:284`, Clones.Heads | Add ValidHub before obtaining a remote or making a network call. It stays hub-only in step 4; removing the guard must fail a GitHub refusal test. |
| `thin/forge.go:544`, StartDefault | Keep ValidHub. No GitHub branch creation or push. |
| `thin/engineer.go:176`, `worker.go:120`, `mergestep.go:50`, `judge.go:44`, `ask.go:732`, `pistep.go:558` | Keep every ValidHub specialist/worker gate, in addition to server recording and dispatch refusal. |
| `thin/relay.go:363,437` | Keep ValidHub at worker handoff and publication. |
| `thin/forge.go:74,115,225` | Keep NewHubRepo for creation and ValidHub in the hub adapter's repository lists. GitHub has its own adapter. |
| `chat/placement.go:57`, `placement_card.go:45`, `tools.go:556` | Keep NewHubRepo. New-project creation remains hub-only. Adding an existing GitHub repository uses its instance inventory binding. |
| `chat/projects.go:469`, `chat/tools.go:957` | Keep HasHubPrefix for hub hello data; also filter hello.catalog before merging. GitHub reach comes only from the instance. |
| `runner/forge/publisher.go:421`, `credential_file.go:79` | Keep ValidHub/HasHubPrefix in legacy publication and hub credential-file handling. |

All `thin/` paths above are under `internal/runner`; `chat/` paths are under
`internal/equipo`. `forgekey.ValidHub`, NewHubRepo and HasHubPrefix themselves
retain their hub-only meaning. Tests prove hub assertions stay unchanged and
that changing any GitHub read call to Push fails locally.

## Fake GitHub contract

Extend the existing `internal/runner/forge/forgetest` package with a GitHub
server and generated RSA keys; do not change its hub merge assertions. Every
unexpected route or verb fails the test. The fake verifies App JWT signature,
issuer, clock bounds, token permissions and exact
repository IDs. Fixture errors carry secret sentinels to test redaction.

| Route | Fake answers and required assertions |
| --- | --- |
| `POST /app-manifests/{code}/conversions` | 201 with generated PEM, App ID, public identifiers and disposable client/webhook sentinels; reused/unknown code 404 or 422; malformed/oversized body, wrong identity, timeout and redirect. Exactly one conversion per state. |
| `GET /app` | 200 matching App/account, exact G4 permissions and no events; mismatched account/App, extra/missing permissions, 401, 403 and 404 refuse activation. |
| `GET /app/installations` | Paginated 200 including unrelated installations; empty while approval pending or after uninstall; reinstall within seven days of first observed loss; matching and duplicate/mismatched account IDs; 401/403/rate limit. Only the verified account can be selected. |
| `GET /app/installations/{id}` | 200 with verified account, App ID, selected or all repositories and no suspension; switching mode remains accepted. Suspended, wrong App/account, 404, 401 and ordinary versus rate-limited 403 are distinct. Redirect ID alone never selects it. |
| `POST /app/installations/{id}/access_tokens` | 201 metadata-only inventory token or one-repository contents/metadata read token, each with bounded expiry and explicit permissions; 401/403/404, deselected repository 422, rate limit, widened permissions, wrong repository and malformed/expired expiry. No write token request is accepted by this fake. |
| `GET /installation/repositories` | 200 with full metadata and ETag, 304 under same and fresh tokens, multiple pages, 1000/1001 rows and misleading totals, changed later page, rename/transfer, deselection, archived/public/private rows; 401, ordinary 403, primary/secondary rate-limited 403, 422, 429 and 5xx. Off-host/cyclic pagination and oversized replies fail closed. |
| `DELETE /installation/token` | 204 followed by 401 for that token; already revoked, timeout and 5xx. Local invalidation still holds if revocation fails. |
| Git smart HTTP GET refs and POST upload-pack | A scoped read token can clone/fetch its selected bare fixture; another repository is denied. Redirect and error output include redaction sentinels. Receive-pack and every repository write API are forbidden and counted. |

For all API routes test redirects without following them, bounded reads,
malformed JSON, cancellation and safe typed errors. Browser redirects are
separately tested through the bound callback handlers; they are not simulated
as authenticated API redirects. No live test uses the probe App's credentials.

The manifest and authentication details were checked against GitHub's
[manifest documentation](https://docs.github.com/en/apps/sharing-github-apps/registering-a-github-app-from-a-manifest),
[App API](https://docs.github.com/en/rest/apps/apps) and
[installation repository API](https://docs.github.com/en/rest/apps/installations#list-repositories-accessible-to-the-app-installation).
The latter requires an installation token, which explains the isolated
metadata-only inventory token above. The approved spec and successful probe
remain the basis for the requested permissions and API version.

## Value-search proof and deliberate mutations

Build one recorder spanning instance logs, HTTP responses, audit rows, stored
records, runner logs, report JSON, all serialized frames, prompts, worker
requests, git argv/config and test workspaces. Search by exact generated value
for the PEM (also its encoded key material), App JWT, installation read token,
inventory token, discarded client/webhook secrets, conversion code, both
redirect states (including URL encoding), and raw/encoded Basic headers.
Seed them into malicious API error bodies and git output too. Only
GitHub credential replies, the broker's private memory, the intended outbound
Authorization/header boundary and the decrypted recipient payload are allowed
plaintext locations for credentials. Code/state may appear only at their
necessary browser redirect/form and inbound callback boundaries, plus the
conversion request path for the code. Scrub request/access logging at those
boundaries. Assert the next Location and rendered page are clean, and no
code/state survives in logs, audit, frames, prompts, reports or stored records
(states are stored as digests). A sealed database value or sealed frame must
not match;
its authenticated decryption is tested separately. Run this across success,
refusal, redirect, timeout, revoked scope, Disconnect races and restart. The
value-search test itself must fail when a sentinel is deliberately logged,
audited, copied into a response/frame/prompt/report or written to disk.

For each branch, add the regression first, observe failure, implement, then
remove each guard individually and require a runtime failure. Record the
exact mutation, killing test, command and restored pass. Minimum guard list:

| Branch | Mutations that must fail |
| --- | --- |
| A | Render a state with no copy or the wrong expiry-stage copy; drop the already-connected message; restrict actions to the starting owner; retain a superseded pending key or omit either audit event; reset/skip the seven-day uninstall deadline or demand Connect after a valid reinstall; remove each token/PEM redaction or secret-scan rule; remove dark-launch flag; remove or globally broaden manifest CSP; use a replica/process-local state claim; expire pending keys at ten minutes or retain them beyond 24 hours; let Check again bypass JWT or require an expired redirect; reuse App-name suffix; hide unreadable-key reconnect state; retain key on failed conversion/Disconnect; leak code/state or skip clean callback redirect; remove owner/CSRF/current-roster checks; accept wrong session/stage or expired/replayed state; reset the ten-minute deadline; trust redirect installation ID; omit App/account/permissions/suspension verification; activate before Connect or admit duplicate active account connections; store plaintext PEM or discarded secrets; swap ciphertext between connections; omit transaction audit; allow late callback to resurrect Disconnect; follow redirects or echo raw errors; omit explicit inventory-token permissions. |
| B | Admit any GitHub task, including a move or flag-off request; exceed 1000 rows or publish a partial/empty snapshot on overflow; hard-code the displayed limit instead of locale formatting; accept each forbidden specialist/worker at recording or dispatch; trust either hello GitHub field; treat rate-limited 403 as revoked; skip primary refresh claim; reject all-repositories mode; revive by name instead of numeric identity; let partial/failed pages erase inventory; ignore page two or accept off-host Link; bypass connection-generation check; treat unknown as zero; change project identity on rename; retain reach after deselection; admit member add; trust repository title/description; send GitHub to hub access handling; clone a reachable non-project; lose the viewer's names/stars; poison a queued turn after disconnection. |
| C | Admit reads with the flag off; bypass DefaultBranch key validation or allow GitHub Heads; bypass per-turn authorization for an existing clone/index; retain clone or index on each lifecycle invalidation or next refusal; republish a late fetch; bypass the A redactor on a new credential path; skip protocol gate/codec refusal; accept a non-primary or removed runner/person; omit one-repository scope or read permissions; reuse a grant after Disconnect; skip post-mint authority recheck; accept expired/replayed/wrong-binding box; leak plaintext into a frame or log; give a sandbox/worker the token; keep a cache past its deadline; permit an operation while authorization is offline; route a GitHub key to the hub; change Read to Push or allow any GitHub write operation. |
| Native | Hide disconnection; drop connection identity; offer owner controls to a member; use an untrusted setup URL; ignore same-revision per-viewer personal-name updates. |

## Gates and handoffs

Use Go 1.26.11, CGO_ENABLED=0 and pinned gofmt. Per branch run fmt-check,
gitleaks, budget, migration-check, copy-release-check, lanes-check, the touched
packages and PersonAPI contracts, plus the full equipo, chat and thintest
suites. The read branch also runs the full runner packages; Linux CI is the
runner gate where macOS lacks Linux containment. Keep native fixtures green.
Raise size ceilings only to measurements with a reason, never to hide a failed
test. Commit with the required co-author trailer, run the reference scan after
committing, push only the feature branch with the helper, and wait for CI.

Every new runtime string goes in copy.go, initially marked pending through
copy-status.py. Send the full key/value list and exact changed API section to
the controller for Luna. Record only the returned verdict, in the inventory
and bounded accepted list; never invoke accept. The full reviewed key/value
list is in [the copy brief](2026-11-23-github-connect-copy.md), with Luna's
2026-11-23 verdict supplied by the controller.
It includes the read-only task refusal, pending-key lifetime, cleanup and
reconnect wording. Any extra or changed runtime string discovered during
implementation requires a further review. The approved pending hint is split
into two exact sentences so the approval instruction appears only for
organizations. Test that it never appears for personal accounts.

Each handoff includes SHA, CI, changed packages/routes/fields, mutation counts,
secret-search results, post-commit reference scan, copy verdicts and remaining
live evidence. After C, the controller's scratch run connects, adds, reads,
answers and disconnects; push/draft/merge portions of the spec's live gate wait
for steps 5 and 6. The old probe document's merge-table and workflow-cause
notes are not silently marked passed by this plan; update them only from the
controller's observed evidence. Preserve Fable's step-5 notes for that phase:
redacting proposal-error logging, proposal retry and done-step reason display.

## Fable review response

| Finding | Plan commitment and evidence required |
| --- | --- |
| P2-1, manifest CSP | A.3 isolates the GitHub form-action exception; header, browser POST/redirect and mutation tests. |
| P2-2, step-4 authority | Recording and dispatch refuse all five specialist/worker classes; Coordinator reads only; no step-read purpose. |
| P2-3, clone/index revocation | Per-turn local-read authorization, explicit six-event lifecycle table, deletion and late-result mutations; plaintext holders and one-hour residual stated. |
| P2-4, pending lifetime | Ten minutes for redirects only, 24 hours for an unconnected key, JWT Check again, key deletion and App cleanup link, fresh random reconnect name. |
| P2-5, shape redaction | A adds all four token prefixes and private-key blocks to redaction and secret-scan coverage, tested without known values. |
| P3, dark launch | Flag defaults off through A/B; production awaits C and live evidence. |
| P3, all repositories | Accepted on Connect and on later admin mode changes. |
| P3, permissions | Contents/metadata read only for project tokens; metadata only for inventory. |
| P3, naming | Forge-connection records and a separate owner-only GitHub section. |
| P3, rate limits and ETags | 403 rate-limit outcomes are stale/retryable, not revoked; fresh-token ETags verified, with memory-only metadata-token reuse if needed. |
| P3, hello and validators | Both hello inventory fields remain hub-only; exact read-relaxed and hub-only source map above. |
| P3, reconnect and misses | Revive by account/repository IDs; deterministic GitHub versus hub versus unresolved-name paths. |
| P3, secrets and recovery | Code/state value-search boundaries, clean callback redirects and typed reconnect on unreadable keys. |
| P3, concurrency | State consumption and refresh claims on primary DB, with cross-process races and stale-completion tests. |
| P3, current base | Main 33fd8660 merged; egress gate met with method recorded, production command confirmation still pending. |

These are future implementation regressions and mutations, not tests claimed
as already run by this documentation revision. No existing test assertions,
runtime strings or wire fields change here.

## Final delta review, 2026-11-23

The controller's follow-up resolves the remaining state and scope questions:

- The [copy brief](2026-11-23-github-connect-copy.md) maps every lifecycle,
  refusal and presentation state to its exact reviewed keys. Implement an
  exhaustive rendering contract: every state emits its required keys, and the
  union of fixture keys equals the 39-key inventory. Remove a mapping to prove
  the test fails. No generic fallback may hide an unmapped state.
- Manifest-stage expiry never offers Check again; installation-stage expiry
  with a retained key does. Both have separate tests and mutations.
- Already-connected and over-limit states use the two additional Luna-approved
  strings. The limit is 1000 repositories, displayed through locale formatting.
- Any current owner may act on a setup after the bound callbacks. Superseding
  a pending setup deletes its key atomically and audits both lifecycle events.
- A connected App later uninstalled retains its key for seven days, with
  verified reinstall recovery and no second Connect tap; expiry deletes it.
- Every GitHub task, including an existing task moved to GitHub, is refused
  independently of the flag. Flag-off also denies reads after data exists.
- DefaultBranch is an authorized GitHub read; Heads receives a hub-only guard.

Each item above is a test-first implementation commitment, with the named
guard deliberately removed before its restored pass is reported. This plan
revision itself changes no runtime behavior.
