Skip to content

Support scoped repository work and typed decisions on Agents Runs - #1083

Merged
cwilhit merged 6 commits into
codex/factory-code-pr-operationsfrom
codex/factory-agent-run-handoff
Nov 12, 2026
Merged

cwilhit merged 6 commits into
codex/factory-code-pr-operationsfrom
codex/factory-agent-run-handoff

Conversation

@cwilhit

@cwilhit cwilhit commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Reuse existing Agents Runs for Factory orchestration. Pin private repository checkout to the admitted commit, use repository-scoped App checkout credentials, export verified runner snapshots, and record typed decisions as bounded result artifacts. Persist invocation ownership and delegated-run lineage for recovery.

Stacked on #1081. Factory admission and lifecycle are reviewed separately in the Providers repository.

Validation

Agents provider Go tests passed locally. Runner tests, lint, hosted CI, and private integration validation are tracked separately while this PR is in draft.

Review verification for 7e13ac77c

  • PostgreSQL 16. TestPostgresRunExecutionLeaseContract passed with AGENTS_TEST_POSTGRES_DSN set. The PostgreSQL test entry point runs the parked approval regression. It asserts that ClaimRun grants a fresh lease, ClaimRecovery rejects a different owner during that lease, and the original owner can proceed. The same PostgreSQL run passed the atomic completion, concurrent delegation admission, and cancellation usage cases.
  • Codex CLI 0.167.1. TestApprovedMCPToolsLoadInCodexAppServer passed locally with RAILGRID_TEST_CODEX_BINARY pointing to that binary. Its real app server returned default_tools_approval_mode = "approve" and enabled_tools = ["code_pull_request"] through config/read.

@cwilhit
cwilhit force-pushed the codex/factory-code-pr-operations branch from 5217383 to 5be5637 Compare November 12, 2026 00:33
@cwilhit
cwilhit force-pushed the codex/factory-agent-run-handoff branch from 412f0bf to 494fe1b Compare November 12, 2026 00:33
@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.

Requested review of the 494fe1b head. No Critical findings. Three Warnings: two are marked Unverified because I traced the code but could not reproduce the interleaving. One more Warning is a missing test. The three Notes are inline. The PR is stacked and in draft; the PR body says runner tests, lint, hosted CI and the private integration are tracked separately.

Not anchored

  • store/store.go (RunArtifact.validate, ~324) bounds nothing on size or media type. The 32 KiB and 16 KiB limits live only in tools/result.go, so any other caller of SaveRunArtifact can store an unbounded blob. This is a Note.
  • The 3-child fan-out cap (delegation_budget.go:23, Limit: 3) is check-then-create, so concurrent delegate calls from one parent can exceed it. This is a Note.
  • codex/mcp.go emits default_tools_approval_mode and enabled_tools. Its test only checks the string is emitted, so nothing confirms the pinned Codex version accepts the key. This is a Note.
  • harness_mcp.go:129-137: when the dispatcher is not a capabilityReader, ApprovedTools is sent anyway, and an older runner rejects the unknown field. This is a Note.
  • Postgres-only SQL (SaveRunOwned, RecordRunUsageOwned, the conflict WHERE clauses) is exercised only when AGENTS_TEST_POSTGRES_DSN is set, and MemoryStore.saveRunLocked is more permissive than Postgres on unowned SaveRun. Memory-store tests can therefore pass on paths that fail on Postgres. This is a Note.

Checked

Read beyond the diff: api/resume.go, api/run_lease.go, api/run_lineage.go, api/recover.go, api/background.go (RecoverRun), api/runprojection.go, api/harness.go, api/harness_mcp.go, api/delegation_*.go, controller/run/controller.go (stranded, claimAndDispatch), controller/connection/controller.go, store/postgres.go and store/memory.go (claim, lease, usage, recovery paths), internal/githubapp/token.go, backend/model/model.go, tools/result.go, pkg/runner/{cleanup,git_result,environment,runner}.go, pkg/runner/harness/{environment.go,systemd_linux.go,codex/*}, pkg/runner/dispatch/events.go, the code provider's manifest and APIExport.

Hunt categories:

  • Correctness: the findings above (ClaimRecovery, the final-message ordering, the usage CAS, Done on MCP errors). Lineage walks are bounded by visited, maxRunLineageRows and a repeated-cursor check.
  • Concurrency: the recovery/resume race and the fan-out cap above. I found no lock-order or goroutine-lifetime problems; the lease heartbeat is bounded by its deadline and context.
  • Tenancy and kcp: every new store method filters org_uuid and workspace_uuid. githubapp.Mint pins repository_ids, read-only contents and metadata, a fixed API base, and refuses redirects. harness.go:716-731 pins repositoryID, auth mode and secret name. No cross-tenant path found. permissionclaimpolicy.yaml, the APIExport copy and the chart files/apiexport.yaml are byte-identical, and the claim is code.railgrid.ai pullrequests get and pullrequests/operate. No serviceaccount or clusterrole claims.
  • Provider contract: manifest.yaml and chart catalogentry.yaml have matching requires: code. dataplane_contract_test.go:372 pins the text. No new routes or bearer verbs.
  • API, codegen and storage: no apis/ change. The new run columns and artifact tables are additive; I found no stored-format break.
  • Security: no credential in logs, errors or status. The checkout token is readable by the agent (see the harness.go Note). The cleanup.go hook log refuses tracked paths and O_EXCL-reopens.
  • Portal: not applicable, since no portal files are in the diff.
  • Tests: new lease, lineage and approval tests discriminate against the change except where listed above. ConformanceTest and the verbs-match-manifest test are unchanged and pass.

Commands:

  • cd providers/agents && go build ./... && go vet ./... && go test -count=1 ./...: all pass. The embed needed a placeholder portal/dist to build, which I added untracked.
  • go build ./pkg/runner/... && go vet ./pkg/runner/... && go test -count=1 ./pkg/runner/...: pass, except pkg/runner/harness TestResolveBinary* (two tests). These fail because /usr/local/bin/claude exists on this host. resolve_test.go is not in the PR.
  • make verify-provider-contract: passes (21/21 node tests; permission claim policy: 0 violations).
  • Not run: make lint, make verify-codegen, make verify-boilerplate, Postgres-backed store tests (no DSN here), and e2e. No apis/ or portal files changed, and the e2e suites for providers need a kcp stack that I did not bring up here.

string(RunPhaseRunning), now.UTC(), observed.UTC())
AND updated_at=$6
AND cancel_requested=FALSE
AND (execution_lease_at IS NULL OR execution_lease_at <= $5::timestamptz - interval '2 minutes')

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: recovery sweep can claim an approval-resume run between ClaimRun and startRunLease
ClaimRun (postgres.go:1436) moves a parked run to Running with execution_owner='' and execution_lease_at=NULL. The run takes its lease only later, in startRunLease (api/run_lease.go:64), after resumeRun has done projection, agent lookup and attachment loading. In that window ClaimRecovery accepts the row because of execution_lease_at IS NULL. The Run controller's stranded() (controller/run/controller.go:~395) judges age from Status.StartedAt/ClaimedAt, not updated_at, so an approval that waited more than ClaimGrace already looks stale, and the projection write from resumeRun re-queues the reconcile. If recovery wins, attempt is bumped and the real resume fails in AcquireRunLease with ErrRunLeaseLost. For a caller-identity run recoverRun then fails it with "caller identity cannot be safely restored". I traced this by reading the code and did not reproduce the interleaving; no test runs a recovery claim between the two steps (execution_lease_test.go runs them in sequence). The memory store has the same rule (memory.go:1317 only guards a non-zero lease).

 AND ((execution_lease_at IS NULL AND updated_at <= $5::timestamptz - interval '2 minutes')
      OR execution_lease_at <= $5::timestamptz - interval '2 minutes')

Apply the same rule in MemoryStore.ClaimRecovery, or have ClaimRun take the lease atomically.

Comment thread providers/agents/api/run.go Outdated
// The final transcript row is a terminal side effect. Write it only after
// this executor wins the owned terminal CAS so a stale lease cannot append
// an answer after a newer owner has taken over the run.
if werr := s.appendTurnFinal(persistCtx, scope, run, sessionID, startedAt, end, tracker, finalContent); werr != nil {

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: Run is reported Succeeded even when its final assistant message cannot be written
finishRunOwned commits Succeeded first, then appendTurnFinal runs and its error is only logged. The PR removed the previous guard (the removed block in the diff) that failed the run when the reply could not be persisted. If appendTurnFinal fails (transient DB error, persistCtx timeout) or the process dies between the two writes, the run is terminal Succeeded and the chat transcript has no answer. The final row also carries the tracker.continuation metadata, so the session loses its continuation. Terminal runs are not revisited by recovery. The ordering comment explains the lease fencing, but the failure mode is not handled.

// Write the final row inside the same owned terminal transaction, or retry it
// idempotently (fixed message ID) and fail the run when it still cannot be written:
if werr := s.appendTurnFinal(persistCtx, scope, run, sessionID, startedAt, end, tracker, finalContent); werr != nil {
    log.Printf("run %s: persisting final assistant message after success: %v", runID, werr)
    s.finishRunOwned(persistCtx, scope, runID, runOutcome{Phase: store.RunPhaseFailed, Message: "persist final assistant message: " + werr.Error()}, end, run.ExecutionOwner, run.Attempt)
}

var usageErr error
if run.ExecutionOwner != "" {
var recorded bool
window, recorded, usageErr = s.store.RecordRunUsageOwned(usageCtx, scope, runID, run.ExecutionOwner, run.Attempt,

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: usage is dropped when a run is cancelled from another replica
RecordRunUsageOwned only updates a row with phase='Running' and the same owner and attempt (postgres.go ~2473). If replica B cancels a run executing on replica A, closeRunNow writes Aborted. When A's turn ends, recorded is false, line 1214 turns that into ErrRunLeaseLost, and line 1222 returns without calling AddUsage. The tokens and cost of a cancelled turn are never charged to the agent's budget window. I traced the SQL and this branch but did not run it against two replicas.

if usageErr == nil && !recorded {
    // The row was settled (e.g. Aborted) under us; still charge the spend.
    window, usageErr = s.store.AddUsage(usageCtx, scope, agent.Name,
        out.Usage.Billed.InputTokens, out.Usage.Billed.OutputTokens, out.Usage.Billed.CostMicros, end, budgetWindow(agent.Spec.Budget))
}


// Reuse the native repository attempt: the runner performs private checkout and
// exports the canonical snapshot, rather than asking the model to clone/commit.
func (s *Server) delegatedRepository(ctx context.Context, d tools.Deps, child *agentsv1alpha1.Agent) (*repositoryAttempt, 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: delegatedRepository has no test
This function decides which repository, commit and credential a delegated child run gets, and it holds the mismatch branches (repositoryID, repository name, task-mode UID). grep -rn delegatedRepository providers/agents finds only the caller in delegation_wait.go:66. TestRepositoryDispatchRequiresPinnedAppCheckoutAuthority covers rejections for the parent path only, and nothing asserts that the minted token lands in run.Repository.Source. Add table tests for a matching connection, a renamed repository, a swapped repositoryID and a task UID mismatch.

return nil, fmt.Errorf("GitHub App connection %q: %w", connName, err)
}
if repositoryID != "" && run.Repository != nil {
run.Repository.Source = &runner.RepositorySource{RemoteURL: repositoryURL, Username: "x-access-token", Token: token}

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: comments now contradict the checkout token handling
The token is stored in run.Repository.Source, and it is also exported as GH_TOKEN and GITHUB_TOKEN a few lines below. The comment at api/background.go (~1034, "never has its clone source") and the repository.go text about the token being included only for the turn describe the old behaviour. A prompt-injected agent can read the repository-scoped read-only token from the environment. Update the comments, and say in the docs that the token is readable by the agent.

for head := 0; head < len(queue); head++ {
cursor := ""
for {
page, err := s.store.QueryRuns(ctx, scope, store.RunQuery{ParentRunID: queue[head], Limit: runDescendantPage, Cursor: cursor})

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: child-run lookups have no supporting index
QueryRuns with ParentRunID filters parent_run_id (store/postgres.go:1711). The only runs indexes are agents_runs_scope_idx (org_uuid, workspace_uuid, created_at DESC) and (phase, updated_at). The Run controller calls ReconcileDescendants on every reconcile of every terminal Run (controller/run/controller.go:252), so a run with no children scans the workspace's run history up to the whole table each time.

`CREATE INDEX IF NOT EXISTS agents_runs_parent_idx ON agents_runs (org_uuid, workspace_uuid, parent_run_id) WHERE parent_run_id <> ''`

Result: firstNonBlank(rec.Item.AggregatedOutput, rec.Item.Output, rec.Item.Result),
Args: firstNonBlank(rec.Item.Command, arguments),
Result: firstNonBlank(rec.Item.AggregatedOutput, rec.Item.Output, resultText),
Failed: mcpResult.IsError,

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: a failed MCP tool item with no status is not marked Done
Failed: mcpResult.IsError sets Failed only. An item with an id, no status field and result.isError=true skips the Done switch below, so ToolEnd (line 447 requires item.Done) is never emitted and the tool stays in flight.

if mcpResult.IsError {
    item.Done = true
}

@cwilhit
cwilhit marked this pull request as ready for review November 12, 2026 00:50
@cwilhit

cwilhit commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@mjudeikis-bot review again

@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.

Re-review of 7e13ac7 (one new commit since my review of 494fe1b). No new Critical or Warning findings. Two Notes inline.

Earlier findings

  • Resolved: ClaimRecovery can claim an approval-resume run before startRunLease. ClaimRun now takes the owner and sets execution_lease_at in the same UPDATE (postgres.go:1531, memory.go ClaimRun), and resumeRun starts the lease right after the claim. The execution_lease_at IS NULL window no longer exists when ProcessID is set, and a claimed run can only be recovered after the 2 minute lease lapses.
  • Resolved: Succeeded reported when the final assistant message cannot be written. CompleteRun commits the Succeeded transition and the final message in one transaction (postgres.go saveRunningRun, memory.go saveRunningRun). A write failure now goes to finishFailedTurn.
  • Resolved: usage dropped when a run is cancelled from another replica. RecordRunUsageOwned accepts Aborted with cancel_requested for the same owner and attempt (postgres.go, memory.go), and runTurn checks leaseWasLost(ctx) after billing.
  • Resolved: delegatedRepository had no test. TestDelegatedRepositoryChecksAdmittedCheckout covers the matching, renamed, swapped-ID and task-UID cases and asserts the minted token lands in run.Repository.Source.
  • Resolved: the comments that contradicted the checkout token handling (background.go, repository.go, harness.go, README) now say the token is readable by the agent. The agents_runs_parent_idx index covers the child lookup. The failed MCP item with no status now sets Done. Artifact size and media type are bounded in RunArtifact.validate. The fan-out cap is now admitted under pg_advisory_xact_lock in checkDelegationAdmission. The review MCP is refused when the dispatcher cannot report capabilities.
  • No reply from the author declined any item.

Hunt, new commit

  • Correctness: the ClaimRun placeholders shift correctly ($8 owner, $9 inbox ID). AcquireRunLease accepts a row whose owner already equals the caller with a fresh lease. With ProcessID empty the owner is "", the lease stays NULL, and CompleteRun with an empty owner matches only an unleased row. The memory and Postgres rules agree.
  • Concurrency: the delegation advisory lock is keyed by org, workspace and parent and held until commit. existing lets an idempotent re-save through. No lock-order change found.
  • Tenancy: the new queries filter org_uuid and workspace_uuid. SaveRun and saveRunningRun now also pin agent_name. delegatedRepository still checks repositoryID, the repository name and the task UIDs.
  • Provider contract, API and codegen, portal: not applicable. The commit adds no route, verb, manifest, CRD or portal change.
  • Security: the checkout token reaches the harness environment, which is now documented. No token in logs, errors or stored rows.
  • Tests: new tests cover delegatedRepository, the lease claim ordering and the Codex config parse.

Not anchored

  • Note: the Postgres paths added here (ClaimRun ... RETURNING, CompleteRun/saveRunningRun, checkDelegationAdmission, the cancelled-usage branch) run only when AGENTS_TEST_POSTGRES_DSN is set (store/postgres_test.go:25). I had no database (docker is denied in this runner), so the SQL is checked by reading only.

Checked

Read beyond the diff: api/run_lease.go (startRunLease, leaseWasLost, newExecutionOwner), store/postgres.go (AcquireRunLease, ReleaseRunLease, ClaimRecovery, SaveRun conflict handling), store/store.go (validateRunCompletion), api/run_progress.go (turnFinalMessage), api/delegation_repository.go, api/delegation_budget.go, api/resume.go, and every caller of ClaimRun and ClaimRecovery.

Commands:

  • cd providers/agents && go vet ./api/... ./store/... ./tools/...: clean. The module root does not build here because assets.go embeds portal/dist, which is not built in this checkout, so I scoped to the changed packages.
  • go test -count=1 ./api/... ./store/... ./tools/... ./controller/... in providers/agents: all pass. Postgres store tests skipped (no DSN).
  • go test -count=1 ./pkg/runner/... at the root: pkg/runner, client, dispatch, harness/claude, harness/codex and runnercli pass. pkg/runner/harness fails TestResolveBinaryLeavesExplicitPathsAndUnknownNamesAlone and TestResolveBinarySkipsNonExecutables because this host has /usr/local/bin/claude. The commit does not touch that package, so this is environmental.
  • Not run: make lint, make verify-* (no apis/, manifest, chart or portalkit change in this commit), and the e2e suites (they need the stack, and the PR notes that private integration is tracked separately).

UPDATE agents_runs SET phase=$4,
updated_at=GREATEST($5::timestamptz, updated_at + interval '1 microsecond'),
started_at=COALESCE(started_at, GREATEST($5::timestamptz, updated_at + interval '1 microsecond')),
execution_owner=$8,

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: the new claim-with-lease transition is only tested on the memory store
ClaimRun now sets execution_owner and execution_lease_at in this UPDATE, and resumeRun relies on it to close the recovery window. The memory-store tests pass, but the Postgres version (CASE expression, RETURNING, the $8/$9 placeholder order) runs only when AGENTS_TEST_POSTGRES_DSN is set. Add a Postgres case to execution_lease_test.go that claims a parked run and then asserts ClaimRecovery is rejected while the fresh lease is live.

// after ClaimRun(owner) on a PendingApproval run:
if _, err := st.ClaimRecovery(ctx, scope, id, claimed.UpdatedAt, "other/owner", claimed.UpdatedAt.Add(time.Second)); err == nil {
	t.Fatal("recovery claimed a freshly leased resume")
}

// Point RAILGRID_TEST_CODEX_BINARY at the binary used by the runner's
// version pin to check its actual app-server configuration parser.
func TestApprovedMCPToolsLoadInCodexAppServer(t *testing.T) {
binary := os.Getenv("RAILGRID_TEST_CODEX_BINARY")

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: the real Codex config check never runs in CI
TestApprovedMCPToolsLoadInCodexAppServer skips unless RAILGRID_TEST_CODEX_BINARY is set, and it was skipped when I ran the package. The default_tools_approval_mode and enabled_tools keys are therefore still unconfirmed against the pinned Codex version unless someone runs it by hand. Record the version you ran it against in the PR, or wire the variable into the runner image job.

@cwilhit
cwilhit merged commit a92c796 into codex/factory-code-pr-operations Nov 12, 2026
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