| 1 | # Connect GitHub: implementation plan, 2026-11-23 |
| 2 | |
| 3 | Plan branch: `github/connect`, updated against main `33fd8660`, which includes |
| 4 | `github/egress-check`. Main is merged without rewriting the published plan. |
| 5 | This branch changes documentation only: this plan, its reviewed copy list and |
| 6 | the probe evidence. The controller requested the revised plan before code. |
| 7 | The full Fable review and the controller's 2026-11-23 rulings are incorporated |
| 8 | below; the rulings supersede the earlier plan's narrower assumptions. |
| 9 | |
| 10 | Authority: the [approved spec](../specs/2026-11-22-equipo-github-connector.md), |
| 11 | G1 to G4, G9 and G10, and the controller's 2026-11-23 step-4 brief. The landed |
| 12 | Projects and card-name corrections remain authoritative: an omitted |
| 13 | `remember_name` skips learning, only an explicit person answer learns, private |
| 14 | names do not override one unique trusted match, and repository text does not |
| 15 | become trusted by saving an unchanged form. |
| 16 | |
| 17 | ## Entry gate and boundaries |
| 18 | |
| 19 | CARLOS egress passed on 2026-11-23 at about 19:12 UTC. The controller ran the |
| 20 | same unauthenticated request from a temporary CARLOS app with Equipo's default |
| 21 | capabilities on the bds fleet, Dublin host annie-welding: status 200, 38ms and |
| 22 | 11ms, TLS peer 4.208.26.200:443. The app was deleted. The |
| 23 | [probe record](../specs/2026-11-22-equipo-github-connector-probe.md) records the |
| 24 | method and control. This meets the implementation entry gate. Running the |
| 25 | landed `check-github` on production after its next upgrade remains a |
| 26 | confirmation, not a claim that this diagnostic has already run there. |
| 27 | |
| 28 | Deliver only connection, repository discovery and reading. No GitHub push, |
| 29 | repository creation, proposal, pull request, hosted-check decision or merge; |
| 30 | no write token. The App requests the approved G4 installation permissions |
| 31 | once, but project tokens in this phase request only contents/read and |
| 32 | metadata/read. Inventory tokens request metadata/read only. Pull request, |
| 33 | checks, status and Actions permissions on tokens wait for step 5. |
| 34 | Future publication and merge will use a separate purpose and lease-bound |
| 35 | sealed write token, never a cached read grant widened in place. |
| 36 | |
| 37 | All branches start from the preceding reviewed and landed main, not from an |
| 38 | unreviewed stack. The controller assigns review and lands each one. No merge |
| 39 | or deployment by the implementing agent. No real probe credentials or files |
| 40 | under `~/private_keys` are read; tests generate their own keys. |
| 41 | |
| 42 | ## Reviewable branches |
| 43 | |
| 44 | | Branch | Reviewable result | Principal test boundary | |
| 45 | | --- | --- | --- | |
| 46 | | `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`. | |
| 47 | | `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. | |
| 48 | | `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. | |
| 49 | | 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. | |
| 50 | |
| 51 | A and B ship behind `EQUIPO_GITHUB=1`, default off. The flag gates the owner |
| 52 | section, setup routes, inventory refresh, Projects additions and the C read |
| 53 | broker. The refusal of GitHub tasks never depends on this flag. Staging may |
| 54 | enable it; production stays off until C and the live read run pass. Test default-off and enabled states, including direct requests. |
| 55 | The first two branches add no runner wire fields. They use the existing |
| 56 | ProjectConnection, ReachableProject, Project and CardLink fields. GitHub |
| 57 | execution stays refused until C supplies the complete guarded read path. |
| 58 | |
| 59 | Step 4 allows only Coordinator search, read_file and answers on GitHub. |
| 60 | Every task on a GitHub project is refused at recording, before dispatch, |
| 61 | including moving an existing task onto a GitHub project. This covers |
| 62 | Engineering, Checks, Copy, Merge and every worker, even with the instance flag |
| 63 | off. Return a tool result, not a frame error. Apply the same admission guard |
| 64 | to web/device task writes, moves and retries, with a defensive dispatch check. |
| 65 | Tests attempt every specialist and worker separately, move an existing hub |
| 66 | task to GitHub, and try recording/moving with the flag off. Assert the refusal |
| 67 | text, unchanged source task on a refused move, and no queued or sent work. |
| 68 | Remove each guard, including the flag-off task and read guards, and require a |
| 69 | failing test. Turning the flag off after data exists refuses reads with |
| 70 | `github.read_unavailable`; it never enables tasks. Hub behavior |
| 71 | stays unchanged. Luna-reviewed copy: `github.read_only`: "Equipo can read this |
| 72 | GitHub project, but cannot change it yet." |
| 73 | |
| 74 | ## A. App connection |
| 75 | |
| 76 | 1. Write lifecycle and HTTP tests first. Add a small instance-only GitHub |
| 77 | client under `internal/equipo/github` and the generated-key fake described |
| 78 | below. Pin `api.github.com`, HTTPS, the probed API version `2022-11-28`, |
| 79 | explicit Accept/User-Agent headers, bounded response bodies, timeouts and |
| 80 | refused redirects. Construct paths from validated IDs; never follow URLs |
| 81 | returned in GitHub JSON. Map errors to bounded typed outcomes, without raw |
| 82 | bodies, URLs containing conversion codes, headers or credentials in logs. |
| 83 | Ship shape redaction and secret-scan coverage in A, before any App secret |
| 84 | is handled: ghs_, ghu_, gho_, ghr_ and PEM private-key headers/blocks, as |
| 85 | detailed in C. Generated samples and an empty known-secret list must still |
| 86 | be protected. Remove each pattern individually to kill its regression. |
| 87 | 2. Add team records for forge connection attempts and forge connections in |
| 88 | additive migrations. Include them in Models and Schema, not BootSchema. Store App |
| 89 | ID, account numeric ID/type/login, installation ID, lifecycle state and a |
| 90 | monotonic generation. Enforce one active private App per team/account with |
| 91 | a database uniqueness guard, including concurrent Connect attempts. Keep |
| 92 | secrets out of all public models. Use the next |
| 93 | free migration numbers on landed main; leave 0100 and 0101 unchanged. |
| 94 | 3. Add an owner-only GitHub section in Settings, separate from model |
| 95 | connections (`connectionRecord`). Use distinct forge-connection model and |
| 96 | store names. Proposed action paths are `/github/connect/start`, |
| 97 | `/github/connect/manifest`, `/github/connect/installation`, |
| 98 | `/github/connect/check`, `/github/connect/confirm` and |
| 99 | `/github/connect/disconnect`. Start, Check again, Connect and Disconnect |
| 100 | are CSRF-protected POSTs. Any current owner may Check again, Connect, |
| 101 | supersede a pending setup or Disconnect; none requires the starting owner. |
| 102 | Check the current roster in each write transaction. Only the two callbacks |
| 103 | remain bound to the initiating owner and session. Callback GETs use state. |
| 104 | Starting again for a pending setup deletes its key in the same transaction |
| 105 | that starts its replacement. Audit both cancellation and creation, show |
| 106 | `github.app_remains` plus the old App cleanup link, and invalidate both old |
| 107 | callback states. Test a different owner superseding the first owner's |
| 108 | attempt, including a concurrent late conversion. Starting for an already |
| 109 | connected account returns `github.already_connected` with the verified |
| 110 | login; it does not create another App. |
| 111 | The start form identifies the intended account and its type; the manifest |
| 112 | posts to GitHub's personal or organisation registration page. Only this |
| 113 | page extends Rastrillo's `form-action 'self'` to |
| 114 | `form-action 'self' https://github.com`; preserve every other directive. |
| 115 | Test the response header and a browser-lane form POST plus redirect chain |
| 116 | back to the clean same-origin page. Route GitHub to the controlled browser |
| 117 | fixture without changing the tested origin policy. Assert another Settings |
| 118 | page cannot submit externally. Remove the exception to kill the browser |
| 119 | test; applying it globally must kill the unrelated-page header test. |
| 120 | 4. Generate unpredictable state, store its digest, bind it to the verified |
| 121 | owner, browser session, instance origin, intended account and attempt. |
| 122 | Use one absolute ten-minute deadline for both redirects. Atomically consume |
| 123 | the first stage before conversion; issue a different single-use state for |
| 124 | installation without extending that deadline. Reject wrong-stage, wrong- |
| 125 | session, expired, replayed and concurrent callbacks. A session losing its |
| 126 | owner role cannot finish an attempt. A failed or uncertain one-use |
| 127 | conversion requires a fresh attempt, never guessed recovery with the code. |
| 128 | Claim state consumption in a primary-database transaction, never on a |
| 129 | replica or in a process-local lock. Concurrent callbacks on two instance |
| 130 | processes must convert only once. Redirect both callbacks immediately to a |
| 131 | clean same-origin status URL without code or state, including failures; |
| 132 | disable caching and referrer propagation on callback responses. |
| 133 | A manifest-stage callback after ten minutes never converts the code and |
| 134 | therefore has no key: show `github.setup_failed` plus `github.app_remains` |
| 135 | and its cleanup link, not Check again. Only installation-stage expiry with |
| 136 | a held key uses `github.redirect_expired` and offers Check again. Test both |
| 137 | stages with an injected clock and assert the exact keys and conversion |
| 138 | count. After the pending key's own 24-hour expiry, use pending-expired |
| 139 | wording instead, with no Check again action. |
| 140 | 5. Manifest: private App, no webhook events, no OAuth-on-install, exact G4 |
| 141 | permissions, instance-owned redirect/setup URLs. Convert the code once. |
| 142 | Keep only the private key and required public identifiers. Discard webhook |
| 143 | and client secrets immediately. Validate the App with its own short-lived |
| 144 | RS256 JWT. Derive a dedicated purpose key from EQUIPO_INSTANCE_KEY using |
| 145 | kernel.PurposeKey; seal the PEM with AEAD and bind ciphertext to the |
| 146 | instance, connection and App ID. Do not reuse a model-credential domain. |
| 147 | An unreadable sealed key yields typed `reconnect`, with no fallback key, |
| 148 | raw decrypt error or retry loop. Test a changed instance key and corrupt |
| 149 | ciphertext. Preserve public identity so the owner can clean up the old App. |
| 150 | 6. Read `/app/installations` and the selected installation using the App JWT. |
| 151 | Match the verified App/account numeric identity, exact permissions and |
| 152 | absence of suspension. For a previously connected App later uninstalled, |
| 153 | keep its key for seven days from the first verified uninstall observation. |
| 154 | While held, any current owner's Check again or the next refresh while in |
| 155 | use can discover a reinstall using the JWT. If the same App/account ID and |
| 156 | approved permissions match and it is not suspended, restore the connection |
| 157 | without a new Connect tap. At seven days delete the key, show |
| 158 | `github.app_remains` and its cleanup link, and require a fresh App to |
| 159 | reconnect. Test reinstall inside the window and expiry outside it, including |
| 160 | account mismatch, unchanged first-seen deadline across refreshes, and races |
| 161 | at the boundary. This seven-day rule is separate from the 24-hour lifetime |
| 162 | of a created-but-never-connected App. Accept both selected-repository and |
| 163 | all-repositories installations, including a later admin switch between them. GitHub's admin |
| 164 | choice plus the owner's Connect sets authority; display GitHub's actual |
| 165 | reachable list. The redirect's ID is a hint, never authority. |
| 166 | Pending org approval stays pending within a separate 24-hour key lifetime |
| 167 | starting at successful conversion. The ten-minute deadline binds only the |
| 168 | two redirects, not Check again or Connect. Within 24 hours, an owner can |
| 169 | use Check again to read the installations with the App JWT, without a new |
| 170 | redirect. Read the complete repository count, show the verified account |
| 171 | and count, and require explicit Connect before making it live. |
| 172 | 7. Recheck the roster, the deadline appropriate to the action, and generation |
| 173 | in every write transaction. Use the transaction handle and explicit allowed fields. |
| 174 | Append each lifecycle write's audit event in that transaction, including |
| 175 | Check again, expiry and availability changes as well as Connect/Disconnect; |
| 176 | an audit failure rolls back its write. Network requests run outside write |
| 177 | transactions, with current authority rechecked before committing results. |
| 178 | Concurrent Disconnect or owner removal wins over late conversion/list/mint |
| 179 | results. At 24 hours for an unconnected App, failed conversion or |
| 180 | Disconnect, or seven days after a verified uninstall without reinstall, |
| 181 | delete key material and invalidate pending grants. Expiry runs through the |
| 182 | trusted maintenance path with the same roster and lifecycle checks; interactive writes recheck |
| 183 | expiry even if maintenance has not run. Disconnect deletes the sealed key, |
| 184 | increments generation and prevents new minting in that transaction. Keep |
| 185 | public identity and projects for the disconnected display. Explain that |
| 186 | the App still exists on GitHub and link its settings for deletion. Use the |
| 187 | verified App slug for its settings URL, or the intended account's Apps |
| 188 | settings list if conversion never established a slug. Do not claim to have |
| 189 | uninstalled it. Reconnect uses a fresh random App-name suffix and verifies |
| 190 | the account again. A new installation revives existing projects only by |
| 191 | matching account ID and repository ID, never login/name alone. |
| 192 | |
| 193 | The count/list API needs an installation token. Use a separate instance-only |
| 194 | inventory token with metadata read and no content or other permissions, |
| 195 | covering the installation's GitHub-authorised repositories. It never goes to a |
| 196 | runner and never becomes a project read token. Test conditional requests with |
| 197 | fresh tokens against the controlled live connection. If token changes prevent |
| 198 | 304s, retain this metadata-only token in instance memory until shortly before |
| 199 | its one-hour expiry; never persist it. Revoke/drop it on invalidation. Cache |
| 200 | ETags per installation, generation and page, not across scope changes. |
| 201 | Omitting the permissions object would inherit writes, so tests must forbid |
| 202 | that. This narrow metadata credential is necessary for the inventory endpoint, |
| 203 | not an exception to one-repository runner tokens. Verify its actual permission |
| 204 | shape against the fake and the controlled live connection before landing A. |
| 205 | |
| 206 | ## B. Reachable repositories and Projects |
| 207 | |
| 208 | 1. Add a reachable-repository table keyed by connection and GitHub numeric |
| 209 | repository ID, and a project binding table retaining that ID. Store the |
| 210 | canonical GitHub spelling, description, default branch, visibility, |
| 211 | archived flag and last push. Preserve project ID, stars, task history, |
| 212 | owner title/description and names through a rename or transfer. A transfer |
| 213 | is reachable only if the verified destination installation includes it; |
| 214 | never infer access from the old name or follow a redirect with credentials. |
| 215 | 2. Refresh in the instance every 55 seconds while the connection's Projects |
| 216 | list or work is in use, hourly otherwise. Define in-use from recent |
| 217 | authenticated views and active GitHub work, using an injected clock and |
| 218 | coalesced refresh. Claim a bounded refresh lease in the primary database |
| 219 | with current roster/generation checks, so two processes cannot refresh the |
| 220 | same connection concurrently. Test takeover of an expired claim and refusal |
| 221 | of stale completions. Support ETags, 100 items per page, and at most 1000 |
| 222 | repositories per installation. A total above that limit, or a 1001st row, |
| 223 | makes the new snapshot unknown, never empty or partially published. Keep |
| 224 | any prior snapshot labelled stale without granting new authority. Show |
| 225 | `github.too_many` beside `github.choose_repositories`; its %s is the bound |
| 226 | formatted with Rastrillo's locale number formatter, never a hard-coded |
| 227 | "1,000". Test a fake listing 1001, including misleading count metadata, |
| 228 | and a locale with different grouping. Allow a bounded overflow probe if the |
| 229 | total is unreliable, to detect the 1001st row without publishing it; do not |
| 230 | keep paginating after overflow. Publish only complete snapshots. Do not |
| 231 | remove repositories because one page failed, or show an unknown count as zero. Rate limiting |
| 232 | and network failure retain labelled stale data but confer no new authority. |
| 233 | Classify both 429 and GitHub's 403 rate-limit form (rate-limit headers, |
| 234 | Retry-After and bounded structured classification) as retryable/stale, |
| 235 | never lost access. Distinguish ordinary forbidden, revoked and suspended |
| 236 | outcomes. A generic 403 does not by itself prove uninstall or deselection. |
| 237 | Reconcile all pages after changes so a changed later page cannot hide behind |
| 238 | a first-page 304. Never follow an off-host pagination link. |
| 239 | 3. Join this instance inventory with the existing hub inventory from the |
| 240 | person's primary runner hello. GitHub discovery works with that runner |
| 241 | offline. Never import GitHub reach from hello.repos or hello.catalog: |
| 242 | filter both to hub entries before joining the instance's GitHub snapshot. |
| 243 | Mutate both filters and prove a forged hello cannot add or revive reach. |
| 244 | ProjectConnection uses `forge: github`, a stable connection ID, |
| 245 | account-labelled title and current state. Available rows use existing |
| 246 | `connection_id`, `forge`, `repo`, `title`, `description` and source fields. |
| 247 | Existing hub IDs, values and allowed-list compatibility remain unchanged. |
| 248 | 4. Owner add checks current roster, connection generation and repository ID in |
| 249 | its transaction and appends its audit row there. Add grants no wider reach. |
| 250 | An ordinary member's tool refusal is a result, never a frame error that |
| 251 | revokes their runner. Disconnect, uninstall, suspension and deselection |
| 252 | preserve projects but mark the connection/project unavailable and remove |
| 253 | add authority. Unknown availability is distinct from disconnection. |
| 254 | 5. Reuse the exact code resolver, trusted-name precedence, bounded placement |
| 255 | cards, personal-name confirmation and turn project block across both |
| 256 | forges. GitHub descriptions remain bounded, redacted, labelled repository |
| 257 | data, never trusted naming instructions. A miss for an explicit canonical |
| 258 | github.com/owner/repo key, or a selected project bound to GitHub, produces |
| 259 | the GitHub card: use Choose repositories on GitHub when a verified |
| 260 | installation exists, otherwise the not-connected notice and web setup link. |
| 261 | A hub key, including the historical bare owner/repo shorthand, follows the |
| 262 | existing hub access request. An unresolved human name goes to placement; |
| 263 | it does not guess a forge or issue an access request. Derive settings links |
| 264 | from validated account/type/ID, never model text. Members can see the link; |
| 265 | GitHub decides who may change the installation. A selection becoming |
| 266 | unavailable must not poison queued turns or lose another turn's reply. |
| 267 | 6. Update `docs/api/equipo-v1.md`, OpenAPI descriptions/examples and native |
| 268 | fixtures for the existing `GET /api/v1/projects` response and add route. |
| 269 | Keep DELETE `/projects/{id}/names`, per-viewer same-revision private-name |
| 270 | events and existing star behavior. No new device write route is needed: |
| 271 | connection setup stays on the web. If implementation requires an extra |
| 272 | device field or route, add its schema and contract tests in the protocol |
| 273 | branch before using it, not as an undocumented side effect here. |
| 274 | |
| 275 | ## C. Read broker, protocol and runner |
| 276 | |
| 277 | 1. Start with wire and mixed-version tests. Main currently speaks protocol 28; |
| 278 | allocate the next free number at implementation, named ProtocolGitHubRead. |
| 279 | Old runners continue hub work but never receive GitHub dispatches, catalog |
| 280 | additions or new frame types. A person asking to read on an old runner gets |
| 281 | the reviewed update notice. Test rejection at dispatch, token request and |
| 282 | encode/decode boundaries, not just a UI predicate. Reject unsupported |
| 283 | GitHub writes even on the new protocol. |
| 284 | 2. Introduce typed `forge_catalog`, `forge_read` and `forge_read_result` frames. |
| 285 | Catalog data contains only active project IDs, validated repository keys |
| 286 | and numeric IDs, connection IDs/generations and availability. It contains |
| 287 | no token and no non-project repository for cloning. A read request carries |
| 288 | an unpredictable request ID, expected project/connection/generation and |
| 289 | purpose (index or Coordinator read), plus the current turn for a |
| 290 | Coordinator read. There is no step-read purpose in this phase. The server |
| 291 | resolves identity and authority itself. Catalog invalidations carry enough |
| 292 | stable identity and generation to delete stale local data; a complete |
| 293 | reconnect snapshot also removes projects absent from it. |
| 294 | 3. The read result carries that request binding, a typed refusal or a sealed |
| 295 | credential, and expiry. Bind ciphertext to the recipient's enrolled seal |
| 296 | key, connection generation, project/repository ID and key, purpose, request |
| 297 | ID and turn where applicable. Use a short delivery deadline |
| 298 | separately from the token's one-hour expiry. Add typed sealbox helpers for |
| 299 | this purpose, preserving model-credential formats. Reject stale, replayed, |
| 300 | cross-runner, cross-repository, cross-generation and altered envelopes. |
| 301 | Results of refusals still complete the request; no hanging tool call. |
| 302 | 4. Broker authority requires EQUIPO_GITHUB=1, a current team member, their |
| 303 | current primary runner, a live connection, active project, reachable numeric repository ID |
| 304 | and applicable current turn. Keep existing execution gates: an active team |
| 305 | owner must exist; the reading requester may be an ordinary member. Every |
| 306 | current member's primary runner may read connected GitHub projects, unlike |
| 307 | the hub's per-agent reach. Authorize each turn before any local clone/index |
| 308 | read, including search_code and read_file when no network fetch is needed. |
| 309 | Mint with exactly one `repository_ids` entry and explicit contents/read |
| 310 | and metadata/read only. Validate returned |
| 311 | scope and expiry before sealing. No broad or write-capable fallback after |
| 312 | a GitHub rejection. Recheck authority after minting; revoke and discard a |
| 313 | token if Disconnect, runner replacement or roster removal won the race. |
| 314 | 5. Keep the runner's token only in private process memory until shortly before |
| 315 | expiry, keyed by the full binding. Reuse only after fresh server |
| 316 | authorization of the turn and each network operation/generation. Inability |
| 317 | to contact the instance denies reading, including cached local content. |
| 318 | Keep an opaque grant ID, never send the token back in a request. On refused |
| 319 | authorization or invalidation, cancel reads, revoke/drop the token and |
| 320 | delete the clone and index entries under the same per-project exclusion |
| 321 | used by reads. Fence late fetch/index results so they cannot republish |
| 322 | deleted data. Apply the lifecycle table below, also after reconnect/restart. |
| 323 | Deleting the sealed App key stops minting but does not erase issued tokens: |
| 324 | the instance holds transient decrypted PEM/JWT during active API calls and |
| 325 | the cached metadata token; the recipient runner holds its project token. |
| 326 | Cancel outstanding calls and drop instance plaintext references at deletion. |
| 327 | The runner revokes its own held token and drops it on notice/refusal; the |
| 328 | instance revokes its metadata token. Best-effort revocation never delays |
| 329 | local denial. Go heap erasure is not guaranteed. A compromised runner can |
| 330 | retain a read token for up to one hour, as the spec accepts, and can keep |
| 331 | content it already copied. Honest-runner deletion does not undo disclosure. |
| 332 | 6. Add a read-only GitHub Forge behind NewForges. Remote(Read) obtains the |
| 333 | broker grant and returns a canonical HTTPS URL with username |
| 334 | `x-access-token`; Remote(Push), Create, Propose and Merge refuse locally |
| 335 | without a network call. Keep the hub's Agent/CreateIn identity and behavior. |
| 336 | Git receives credentials only via the existing environment header path, |
| 337 | with redirects refused and URL/config rewrites guarded. Redact raw and |
| 338 | encoded Basic credentials, including the username, before any git failure |
| 339 | leaves the process. Reuse the A shape redactor in runnerproto/event_io.go |
| 340 | and secret-scan fixtures for ghs_, ghu_, gho_, ghr_ and PEM private-key |
| 341 | headers/blocks (including truncated blocks), alongside existing patterns. |
| 342 | Test without a known-secret list and kill each removed pattern. Exercise |
| 343 | the pinned gitleaks scan with generated shape samples too; if a pattern is |
| 344 | missing, add an explicit trusted rule rather than weakening scan policy. |
| 345 | No token in argv, disk, repository config, sandbox, |
| 346 | Mac worker request, prompt or report. |
| 347 | 7. Index only active reachable GitHub projects. Exercise actual clone, fetch, |
| 348 | default-branch discovery and bounded read/index against a local Git HTTP |
| 349 | fixture; a Coordinator then answers about the fetched content. Inventory |
| 350 | text and repository content retain the current injection defenses. Tests |
| 351 | cover expiry refresh, deselection, disconnect during clone, primary runner |
| 352 | replacement, missing connection, and two forges with the same basename. |
| 353 | |
| 354 | ## Local data lifecycle and read guards |
| 355 | |
| 356 | On a live socket, send an invalidation as soon as the instance commits the |
| 357 | change. A disconnected runner applies the complete catalog on reconnect; a |
| 358 | runner missing that notice must delete on its next refused read authorization. |
| 359 | Index scheduling also needs current authority, even without a person turn. |
| 360 | No local read may bypass authorization because a directory already exists. |
| 361 | Tests start with both a populated clone and published index, then assert both |
| 362 | are absent and no stale result is returned. Test notification and missed-notice |
| 363 | paths separately, including failure to delete: deny reads until cleanup works. |
| 364 | |
| 365 | | Change | Instance decision | Honest runner action | |
| 366 | | --- | --- | --- | |
| 367 | | 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. | |
| 368 | | 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. | |
| 369 | | 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. | |
| 370 | | 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. | |
| 371 | | 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. | |
| 372 | | 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. | |
| 373 | |
| 374 | After reconnect, revive projects by the verified account ID plus repository |
| 375 | ID. A renamed account or repository can match; reuse of an old name with new |
| 376 | IDs cannot. A transfer to another account needs that account's verified |
| 377 | connection and reach. The old binding alone grants nothing. |
| 378 | |
| 379 | Source locations below are against main `33fd8660`. The shared fetch |
| 380 | validator is widened; DefaultBranch gets explicit read-key validation, and |
| 381 | Heads gets a hub-only guard. Caller authority is tightened separately. The |
| 382 | closed forgekey host list, router no-fallback behavior and hub identity stay intact. |
| 383 | |
| 384 | | Guard / path | Step-4 treatment | |
| 385 | | --- | --- | |
| 386 | | `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. | |
| 387 | | `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. | |
| 388 | | `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. | |
| 389 | | `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. | |
| 390 | | `thin/forge.go:544`, StartDefault | Keep ValidHub. No GitHub branch creation or push. | |
| 391 | | `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. | |
| 392 | | `thin/relay.go:363,437` | Keep ValidHub at worker handoff and publication. | |
| 393 | | `thin/forge.go:74,115,225` | Keep NewHubRepo for creation and ValidHub in the hub adapter's repository lists. GitHub has its own adapter. | |
| 394 | | `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. | |
| 395 | | `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. | |
| 396 | | `runner/forge/publisher.go:421`, `credential_file.go:79` | Keep ValidHub/HasHubPrefix in legacy publication and hub credential-file handling. | |
| 397 | |
| 398 | All `thin/` paths above are under `internal/runner`; `chat/` paths are under |
| 399 | `internal/equipo`. `forgekey.ValidHub`, NewHubRepo and HasHubPrefix themselves |
| 400 | retain their hub-only meaning. Tests prove hub assertions stay unchanged and |
| 401 | that changing any GitHub read call to Push fails locally. |
| 402 | |
| 403 | ## Fake GitHub contract |
| 404 | |
| 405 | Extend the existing `internal/runner/forge/forgetest` package with a GitHub |
| 406 | server and generated RSA keys; do not change its hub merge assertions. Every |
| 407 | unexpected route or verb fails the test. The fake verifies App JWT signature, |
| 408 | issuer, clock bounds, token permissions and exact |
| 409 | repository IDs. Fixture errors carry secret sentinels to test redaction. |
| 410 | |
| 411 | | Route | Fake answers and required assertions | |
| 412 | | --- | --- | |
| 413 | | `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. | |
| 414 | | `GET /app` | 200 matching App/account, exact G4 permissions and no events; mismatched account/App, extra/missing permissions, 401, 403 and 404 refuse activation. | |
| 415 | | `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. | |
| 416 | | `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. | |
| 417 | | `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. | |
| 418 | | `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. | |
| 419 | | `DELETE /installation/token` | 204 followed by 401 for that token; already revoked, timeout and 5xx. Local invalidation still holds if revocation fails. | |
| 420 | | 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. | |
| 421 | |
| 422 | For all API routes test redirects without following them, bounded reads, |
| 423 | malformed JSON, cancellation and safe typed errors. Browser redirects are |
| 424 | separately tested through the bound callback handlers; they are not simulated |
| 425 | as authenticated API redirects. No live test uses the probe App's credentials. |
| 426 | |
| 427 | The manifest and authentication details were checked against GitHub's |
| 428 | [manifest documentation](https://docs.github.com/en/apps/sharing-github-apps/registering-a-github-app-from-a-manifest), |
| 429 | [App API](https://docs.github.com/en/rest/apps/apps) and |
| 430 | [installation repository API](https://docs.github.com/en/rest/apps/installations#list-repositories-accessible-to-the-app-installation). |
| 431 | The latter requires an installation token, which explains the isolated |
| 432 | metadata-only inventory token above. The approved spec and successful probe |
| 433 | remain the basis for the requested permissions and API version. |
| 434 | |
| 435 | ## Value-search proof and deliberate mutations |
| 436 | |
| 437 | Build one recorder spanning instance logs, HTTP responses, audit rows, stored |
| 438 | records, runner logs, report JSON, all serialized frames, prompts, worker |
| 439 | requests, git argv/config and test workspaces. Search by exact generated value |
| 440 | for the PEM (also its encoded key material), App JWT, installation read token, |
| 441 | inventory token, discarded client/webhook secrets, conversion code, both |
| 442 | redirect states (including URL encoding), and raw/encoded Basic headers. |
| 443 | Seed them into malicious API error bodies and git output too. Only |
| 444 | GitHub credential replies, the broker's private memory, the intended outbound |
| 445 | Authorization/header boundary and the decrypted recipient payload are allowed |
| 446 | plaintext locations for credentials. Code/state may appear only at their |
| 447 | necessary browser redirect/form and inbound callback boundaries, plus the |
| 448 | conversion request path for the code. Scrub request/access logging at those |
| 449 | boundaries. Assert the next Location and rendered page are clean, and no |
| 450 | code/state survives in logs, audit, frames, prompts, reports or stored records |
| 451 | (states are stored as digests). A sealed database value or sealed frame must |
| 452 | not match; |
| 453 | its authenticated decryption is tested separately. Run this across success, |
| 454 | refusal, redirect, timeout, revoked scope, Disconnect races and restart. The |
| 455 | value-search test itself must fail when a sentinel is deliberately logged, |
| 456 | audited, copied into a response/frame/prompt/report or written to disk. |
| 457 | |
| 458 | For each branch, add the regression first, observe failure, implement, then |
| 459 | remove each guard individually and require a runtime failure. Record the |
| 460 | exact mutation, killing test, command and restored pass. Minimum guard list: |
| 461 | |
| 462 | | Branch | Mutations that must fail | |
| 463 | | --- | --- | |
| 464 | | 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. | |
| 465 | | 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. | |
| 466 | | 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. | |
| 467 | | 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. | |
| 468 | |
| 469 | ## Gates and handoffs |
| 470 | |
| 471 | Use Go 1.26.11, CGO_ENABLED=0 and pinned gofmt. Per branch run fmt-check, |
| 472 | gitleaks, budget, migration-check, copy-release-check, lanes-check, the touched |
| 473 | packages and PersonAPI contracts, plus the full equipo, chat and thintest |
| 474 | suites. The read branch also runs the full runner packages; Linux CI is the |
| 475 | runner gate where macOS lacks Linux containment. Keep native fixtures green. |
| 476 | Raise size ceilings only to measurements with a reason, never to hide a failed |
| 477 | test. Commit with the required co-author trailer, run the reference scan after |
| 478 | committing, push only the feature branch with the helper, and wait for CI. |
| 479 | |
| 480 | Every new runtime string goes in copy.go, initially marked pending through |
| 481 | copy-status.py. Send the full key/value list and exact changed API section to |
| 482 | the controller for Luna. Record only the returned verdict, in the inventory |
| 483 | and bounded accepted list; never invoke accept. The full reviewed key/value |
| 484 | list is in [the copy brief](2026-11-23-github-connect-copy.md), with Luna's |
| 485 | 2026-11-23 verdict supplied by the controller. |
| 486 | It includes the read-only task refusal, pending-key lifetime, cleanup and |
| 487 | reconnect wording. Any extra or changed runtime string discovered during |
| 488 | implementation requires a further review. The approved pending hint is split |
| 489 | into two exact sentences so the approval instruction appears only for |
| 490 | organizations. Test that it never appears for personal accounts. |
| 491 | |
| 492 | Each handoff includes SHA, CI, changed packages/routes/fields, mutation counts, |
| 493 | secret-search results, post-commit reference scan, copy verdicts and remaining |
| 494 | live evidence. After C, the controller's scratch run connects, adds, reads, |
| 495 | answers and disconnects; push/draft/merge portions of the spec's live gate wait |
| 496 | for steps 5 and 6. The old probe document's merge-table and workflow-cause |
| 497 | notes are not silently marked passed by this plan; update them only from the |
| 498 | controller's observed evidence. Preserve Fable's step-5 notes for that phase: |
| 499 | redacting proposal-error logging, proposal retry and done-step reason display. |
| 500 | |
| 501 | ## Fable review response |
| 502 | |
| 503 | | Finding | Plan commitment and evidence required | |
| 504 | | --- | --- | |
| 505 | | P2-1, manifest CSP | A.3 isolates the GitHub form-action exception; header, browser POST/redirect and mutation tests. | |
| 506 | | P2-2, step-4 authority | Recording and dispatch refuse all five specialist/worker classes; Coordinator reads only; no step-read purpose. | |
| 507 | | 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. | |
| 508 | | 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. | |
| 509 | | P2-5, shape redaction | A adds all four token prefixes and private-key blocks to redaction and secret-scan coverage, tested without known values. | |
| 510 | | P3, dark launch | Flag defaults off through A/B; production awaits C and live evidence. | |
| 511 | | P3, all repositories | Accepted on Connect and on later admin mode changes. | |
| 512 | | P3, permissions | Contents/metadata read only for project tokens; metadata only for inventory. | |
| 513 | | P3, naming | Forge-connection records and a separate owner-only GitHub section. | |
| 514 | | 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. | |
| 515 | | P3, hello and validators | Both hello inventory fields remain hub-only; exact read-relaxed and hub-only source map above. | |
| 516 | | P3, reconnect and misses | Revive by account/repository IDs; deterministic GitHub versus hub versus unresolved-name paths. | |
| 517 | | P3, secrets and recovery | Code/state value-search boundaries, clean callback redirects and typed reconnect on unreadable keys. | |
| 518 | | P3, concurrency | State consumption and refresh claims on primary DB, with cross-process races and stale-completion tests. | |
| 519 | | P3, current base | Main 33fd8660 merged; egress gate met with method recorded, production command confirmation still pending. | |
| 520 | |
| 521 | These are future implementation regressions and mutations, not tests claimed |
| 522 | as already run by this documentation revision. No existing test assertions, |
| 523 | runtime strings or wire fields change here. |
| 524 | |
| 525 | ## Final delta review, 2026-11-23 |
| 526 | |
| 527 | The controller's follow-up resolves the remaining state and scope questions: |
| 528 | |
| 529 | - The [copy brief](2026-11-23-github-connect-copy.md) maps every lifecycle, |
| 530 | refusal and presentation state to its exact reviewed keys. Implement an |
| 531 | exhaustive rendering contract: every state emits its required keys, and the |
| 532 | union of fixture keys equals the 39-key inventory. Remove a mapping to prove |
| 533 | the test fails. No generic fallback may hide an unmapped state. |
| 534 | - Manifest-stage expiry never offers Check again; installation-stage expiry |
| 535 | with a retained key does. Both have separate tests and mutations. |
| 536 | - Already-connected and over-limit states use the two additional Luna-approved |
| 537 | strings. The limit is 1000 repositories, displayed through locale formatting. |
| 538 | - Any current owner may act on a setup after the bound callbacks. Superseding |
| 539 | a pending setup deletes its key atomically and audits both lifecycle events. |
| 540 | - A connected App later uninstalled retains its key for seven days, with |
| 541 | verified reinstall recovery and no second Connect tap; expiry deletes it. |
| 542 | - Every GitHub task, including an existing task moved to GitHub, is refused |
| 543 | independently of the flag. Flag-off also denies reads after data exists. |
| 544 | - DefaultBranch is an authorized GitHub read; Heads receives a hub-only guard. |
| 545 | |
| 546 | Each item above is a test-first implementation commitment, with the named |
| 547 | guard deliberately removed before its restored pass is reported. This plan |
| 548 | revision itself changes no runtime behavior. |
| 549 | |