Skip to content

Add scoped GitHub pull request operations to Code - #1081

Merged
cwilhit merged 6 commits into
mainfrom
codex/factory-code-pr-operations
Nov 12, 2026
Merged

cwilhit merged 6 commits into
mainfrom
codex/factory-code-pr-operations

Conversation

@cwilhit

@cwilhit cwilhit commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator

Summary

Add App-backed pull request observations and scoped publication for Factory. Grants bind repository, PR, branch, caller, invocation, and deadline. Code validates the expected head before applying snapshots or posting inline review findings. CI includes workflow-level conclusions.

The external GitHub comment webhook is a follow-up. This draft is the Code dependency for the Factory ad-hoc and Agents handoff changes.

Validation

  • Code provider Go tests and Railgrid provider-contract checks passed locally.
  • Hosted CI and cross-repository validation are pending.

@cwilhit
cwilhit force-pushed the codex/factory-code-pr-operations branch from 5217383 to 5be5637 Compare November 12, 2026 00:33
@cwilhit
cwilhit marked this pull request as ready for review November 12, 2026 00:36
@cwilhit
cwilhit requested a review from mjudeikis as a code owner November 12, 2026 00:36
@cwilhit

cwilhit commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@mjudeikis-bot review

@mjudeikis mjudeikis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No verified Critical findings. Two Warnings are traced through the code but not reproduced (both titled "Unverified"), plus three Notes and one unanchored Note.

Not anchored

  • Note: the new verbs githubevents/context, pullrequests/operate and repositories/authorize have no dataplane.ConformanceTest (AGENTS.md §606, §732). grep -rn ConformanceTest --include=*.go finds no definition or caller anywhere in the tree, so I could not run one. The PR's own tests (server_test.go, native_routing_test.go) cover routing and the happy/refusal paths, but nothing asserts the Gate-then-act-as-provider order for these three verbs. Worth either adding the harness call or noting where it will land.

Checked

Read beyond the diff:

  • githubworkflow/{server,operations,task_authorization,github,ci,inline_review}.go in full; controller/pullrequest/controller.go Reconcile, advance, open, fail; backend/interface.go Registry.Get; backend/github/snapshot.go guarded push; main.go codeDataPlaneHandler; controller_manager.go wiring; catalogentry.go route filtering; manifest.yaml vs deploy/chart/templates/catalogentry.yaml.
  • Callers of Server.Webhook: none outside tests (the PR body says the webhook is a follow-up).

Hunt outcomes:

  • Correctness: spec.number adoption (controller.go:189); CI summary double counting (ci.go:80); comment op on an unopened PR (task_authorization.go:692). Revocation/tombstone ordering, deadline checks, hmac.Equal use, strict JSON decoding (DisallowUnknownFields + trailing-data check) and the guarded push (advanceGuarded + --force-with-lease) all read correct.
  • Concurrency: grant/revoke/publish all write via Update with the read resourceVersion, so concurrent writers conflict rather than overwrite. No new goroutines or shared maps. The reconciler is watch-driven; RequeueAfter is used only for forge observation. No finding.
  • Tenancy/kcp: every client call goes through Callers.AsProvider(cluster) with the cluster from the route/request; AuthorizeTask requires IsForeignProvider(cluster). The proof-key trust model is the Unverified Warning on task_authorization.go:176. No new permission claims, no serviceaccounts/clusterroles claims.
  • Provider contract: verbs are served behind dataplane.Gate; no bearer on a verb, no /api/* route; ServedVerbs matches manifest.yaml and the chart catalogentry.yaml (checked by the existing catalog/subresource tests, which pass). Missing conformance harness noted above.
  • API/codegen/storage: make codegen-code-provider regenerates with a clean git status (deepcopy, config/crds, config/kcp, chart files/). New fields are optional with validation markers; taskAuthorizationRevocations is a listType=map keyed on sourceUID. No removed or renamed fields.
  • Security: X-Remote-* identity comes from dataplane.ProxiedIdentityFrom; GitHub client pins https://api.github.com, refuses redirects, bounds response size; credentials are not placed in errors or status. The unrouted Webhook handler and its pre-signature reads are the Note on server.go:173.
  • Portal: not applicable, no portal files in the diff.
  • Tests: the controller revocation race test, TestPublicationUsesFrozenScopeAndExpectedParent, TestCleanReviewSuppressedAtCodeBoundary and the guarded-push test each fail without the change they cover. No test covers spec.number adoption with command == nil.

Commands run (providers/code unless stated):

  • go vet ./githubworkflow/... ./controller/... ./apis/... ./backend/...: clean.
  • go test -count=1 ./githubworkflow/... ./controller/... ./apis/... ./backend/... ./actions/...: all ok.
  • go build ./... / full go test ./...: not completed, assets.go:22 embeds portal/dist, which is not built in this checkout. The root package tests (native_routing_test.go, subresource_test.go, actions_catalog_test.go) were therefore not run by me; make verify-provider-contract exercises the manifest/chart parity and passed.
  • make codegen-code-provider: no diff afterwards; ./hack/ensure-boilerplate.sh: all files have the boilerplate.
  • make verify-provider-contract: 21/21 pass, 0 permission-claim violations.
  • Root make build/make lint and make verify-portalkit: not run (no root Go, portalkit or portal changes).

E2E: not run. I did not find a Code-provider e2e target in the AGENTS.md §7 table that exercises GitHub App connections, and the hosted CI / cross-repo validation the PR body marks pending would be the place for that.

}

// 1. The branch: advance it to the desired head when it is not there.
if pr.Status.Number == 0 && pr.Spec.Number > 0 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning: Unverified: tenant-set spec.number bypasses the "branch is not this PR's to move" guard
spec.number is tenant-writable with only Minimum=1. Reconcile 1: a PullRequest with spec.number=N, spec.branch=<existing feature branch> and no desiredHead takes this branch, sets next.Status.Number=N, and step 3 then writes Status.Head = observed.Commit (the foreign branch head) after the observed.Head != pr.Spec.Branch check passes. Reconcile 2: the tenant sets desiredHead with baseCommit equal to that head; advance now sees Status.Number != 0, expected == current, so the expected == "" && Status.Number == 0 && current != "" refusal at line ~393 no longer applies and PublishSnapshot force-with-leases the branch. Later title/body edits also go through UpdatePullRequest on a PR the resource never opened. I traced this but did not run it; if it holds, adoption should be limited to spec.command PRs (or the existing-branch refusal kept for adopted PRs).

if pr.Status.Number == 0 && pr.Spec.Number > 0 && pr.Spec.Command != nil {
	next.Status.Number = pr.Spec.Number
	textChanged = false
	next.Status.PublishedTextDigest = digest
}

A CEL rule on spec.number requiring has(self.command) would enforce the same at admission.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in 022c178. Reproduced: a PullRequest with spec.number and no command adopted a foreign open PR and recorded its head as status.head, so the next desired head would have force-pushed it. Adoption now requires spec.command, the verified-command path where CheckPublication also requires spec.number to match the event's PR. Without a command the resource fails with "spec.number adopts an existing pull request only for a verified command". TestNumberAdoptionRequiresAVerifiedCommand fails on the previous controller. I enforced this in the controller rather than with a CEL rule, because a CEL rule would bump the PullRequest schema; I can add one if you want the check at admission time too.

// taskSigningKey derives a Code-side key from the App webhook signing secret.
// The secret is present in the App binding already used to verify signed forge
// deliveries; domain separation keeps task authority proofs distinct.
func taskSigningKey(conn *api.Connection, data map[string][]byte) ([]byte, error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning: Unverified: grant proofs are keyed from the tenant-held webhook secret and stored in tenant-writable spec
taskSigningKey derives the HMAC key from data["webhookSecret"], read from the Connection's Secret in the tenant workspace, and both the grant (spec.command.task, with proof) and the tombstones (spec.taskAuthorizationRevocations) live in the PullRequest spec. Anyone who can read that Secret and update PullRequests can compute a valid proof/grantRef and scopeProof, add a grant for a caller of their choosing, or delete a tombstone to undo a revocation. The comments on PullRequestTaskAuthorization say tenant-authored values are not trusted without a valid proof, which only holds if that principal cannot read the Secret. I could not confirm which principals (for example an Agents runner service account) can read the Secret or update pullrequests in a consumer workspace, so this may be acceptable under the intended trust model; it deserves an explicit statement in docs/security.md or a key that is not tenant-readable (provider-held secret, or a status/private-kind record instead of spec).

// derive from a provider-held secret, not the tenant Secret
func taskSigningKey(providerKey []byte, conn *api.Connection) ([]byte, error) {
	if len(providerKey) < 32 {
		return nil, errors.New("task authority signing key is unavailable")
	}
	// ...same domain-separated SHA-256 over conn.UID + providerKey
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked; not an escalation, but the trust model is now stated (README, "Coordinator task grants", 022c178). The Connection Secret that keys the proofs also holds the GitHub App private key (installationToken reads it from the same data). A principal who can read it can already act as the App on GitHub directly, so forging a grant adds no GitHub power. Inside Railgrid, every use of a grant re-runs the SubjectAccessReview for the named caller's create pullrequests/operate (authorizeTaskCaller), so a forged grant only borrows an already-authorized caller's authority. What remains is misattribution: work can be attributed to a caller who didn't request it. The README says this and says to limit Secret read and pullrequests update to principals trusted with the App key. A provider-held key with grants in provider-owned state would close that gap; it isn't implemented here.

Comment thread providers/code/githubworkflow/ci.go Outdated
}
pending += workflowPending
failed += workflowFailed
summary = fmt.Sprintf("CI observation on `%s`: %d check runs (%d pending, %d failed, %d skipped/neutral); %d commit-status contexts. This observes available CI, not a merge approval or an assertion about unseen policy.", sha, count, pending, failed, skipped, status.Total)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: CI summary counts workflow runs in the check-run totals
pending += workflowPending and failed += workflowFailed (lines 78-79) run before the summary is formatted, so the first sentence reports "N check runs (P pending, F failed ...)" with P and F that include workflow runs, and the second sentence reports the workflow counts again. A repo with 3 check runs and 1 failed workflow run is reported as "3 check runs (... 1 failed)" and "1 current workflow runs (... 1 failed)", which misleads an operator reading it. Keep separate counters for the totals that drive state.

totalPending, totalFailed := pending+workflowPending, failed+workflowFailed
// format the check-run sentence with pending/failed, the workflow sentence with workflowPending/workflowFailed,
// and switch on totalFailed/totalPending

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 022c178. Check runs, commit-status contexts (now reported with their combined state) and workflow runs each keep their own counts in the summary, and only the combined totals decide state. TestCISummaryKeepsSourcesSeparate covers your example of 3 green check runs plus 1 failed workflow.

if len(in.Body) > 16384 {
return nil, errors.New("PR status comment exceeds the Code limit")
}
e := &api.GitHubEvent{Spec: api.GitHubEventSpec{Repository: repositoryName(binding{repo: b.repo, conn: b.conn}), PullRequest: effectivePullRequestNumber(fresh)}}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: comment on a task PR that is not opened yet posts to /issues/0/comments
effectivePullRequestNumber(fresh) is 0 until the PR is created (the Status.Number/Spec.Number fallback at line 812), so a grant issuer calling operate with op: comment before the first publish builds /repos/<repo>/issues/0/comments. GitHub answers 404 and the caller sees "GitHub API returned HTTP 404", which points at the forge rather than the real cause. Refuse up front, as taskPullRequest already does for review.

number := effectivePullRequestNumber(fresh)
if number <= 0 {
	return nil, errors.New("PR has not been opened yet; no status comment target")
}
e := &api.GitHubEvent{Spec: api.GitHubEventSpec{Repository: repositoryName(binding{repo: b.repo, conn: b.conn}), PullRequest: number}}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 022c178. comment now refuses with "the pull request has not been opened yet; there is no status comment target" when there is no PR number. TestTaskStatusCommentRequiresAnOpenedPullRequest fails on the previous code.

reply(w, 503, map[string]string{"error": "workspace unavailable"})
return
}
b, err := s.binding(ctx, dyn, name, false)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: Webhook is unrouted, and does tenant-cluster reads before the signature check
Nothing in this PR registers Server.Webhook (no caller outside tests; the PR body says the webhook is a follow-up), so the handler, duplicateReceipt and the Events create path are dead code in production until then. When it is wired up, s.binding runs first: an unauthenticated request to /{cluster}/{name} costs a Connection get, a Secret load and a Repository get, and answers 404 for unknown connections but 403 for known ones, which tells a caller which connection names exist. Consider verifying the signature against a cached secret first, or returning the same status for both cases, and rate limiting the route when it is added.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handled in #1082, which mounts the route. There, every failure before the signature check returns the same 404 not found, with the cause logged server-side. The body is read and size-checked before any lookup, so an oversized unsigned request can't reveal a connection either. The route is tested through serve.New. Rate limiting the route is still open.

cwilhit and others added 3 commits November 11, 2026 20:12
)

* Support scoped repository work and typed decisions on Agents Runs

* Keep Factory PR delegates on pinned per-run checkouts

* Address Agents run handoff review findings

* Fix Agents run lifecycle and trace review findings

* Protect Code invocation scopes and repair resumed Run lifecycle

* Recover unprojected approvals and preserve repository deadlines
- Delegation: start a child Run detached from the parent's tool-call
  context, so a parent timeout or lost lease no longer strands the child
  in Running; the parent still cancels the child explicitly.
- startRun: a Pending row this request recorded but could not claim is
  failed with the real cause (or returned as admitted when another
  executor claimed it), instead of being handed to an idempotent retry
  as Reused with nothing executing it.
- Terminal writes: retry transient store failures while the lease is
  still held, treat only a lost lease as lease loss, and accept a retry
  that finds an earlier attempt already committed.
- Retry handback: an owned save that returns a run to Pending clears
  execution_owner and execution_lease_at itself, so a failed deferred
  ReleaseRunLease can no longer leave an unclaimable queued run.
- Postgres: pass RunLeaseDuration to every lease-validity predicate
  instead of a hard-coded interval '2 minutes'.
- Recovery: a run admitted before agent_uid existed takes its frozen
  Agent UID from the Run's owner reference, verified against the live
  Agent, instead of being failed.
- Warm environments: the five-minute retry window bounds the retries,
  not each Start, and a spent window returns the runner's refusal so the
  run-level retry still requeues the run.
- Run controller: a terminal parent waiting on children to settle is
  re-enqueued by a watch on child Runs reaching a terminal phase, not a
  30s RequeueAfter; real failures keep the backoff.
- Remove duplicate helpers: AddDelegatedUsage uses ensureTransaction,
  terminal-phase and execution-owner checks have one implementation, and
  the aborted invocation record uses RunTriggerAPI.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 11062a4)
- PullRequest: spec.number adopts an existing forge PR only for a
  verified command. Adoption without one made a foreign branch's head
  this resource's to move, bypassing the existing-branch refusal and
  letting the next desired head force-push it.
- Task status comments refuse a PR that has not been opened yet instead
  of posting to /issues/0/comments and surfacing GitHub's 404.
- CI observation reports check runs, commit statuses and workflow runs
  with their own counts; only the combined totals decide the state.
- README: state the task-grant trust boundary. The signing key derives
  from the tenant-held Connection Secret, which also holds the App
  private key; a forged grant borrows only an authorized caller's
  authority because every use re-runs the SubjectAccessReview.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cwilhit

cwilhit commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

Re the unanchored note about dataplane.ConformanceTest: confirmed. It's referenced in AGENTS.md and docs/roadmap/provider-contract-remediation.md but doesn't exist anywhere in the tree, so no provider can call it yet. Covering the Gate-then-act-as-provider order for githubevents/context, pullrequests/operate and repositories/authorize waits on that harness landing.

This branch also now carries 7e5a714c2, the run-ownership fixes from the #1083 review. #1083 was merged here before they were pushed.

cwilhit and others added 2 commits November 11, 2026 21:38
The Agents CatalogEntry named Code in spec.requires so the code_pull_request
tool could call pullrequests/{name}/operate as the Agents provider. A
requirement naming a provider is also a dependency edge, so the hub refused
to enable Agents in any workspace without Code (the agentsprovider e2e 409).

The tool now calls Code as a hub-minted identity owned by the executing Run,
with get and operate on the one admitted PullRequest only. Where Code is not
enabled the hub refuses the mint and only the Code tool fails, saying why.
Agents drops the claim, the dependency and the permission-claim-policy entry.

Code accepts that identity for task operations alongside a foreign provider:
it recomputes the ServiceAccount name the hub gives the Run's identity, now
shared as identityclient.ServiceAccountName, from invocationRun and
invocationRunUID in the operation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cwilhit
cwilhit merged commit 011806d into main Nov 12, 2026
51 checks passed
cwilhit added a commit that referenced this pull request Nov 12, 2026
Revert PR #1082 and the first-parent changes from PR #1081, including PR #1083. Preserve the unrelated changes on main through #1056.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants