Skip to content

Commit 14f7305

Browse files
authored
Merge pull request #30 from dapi/feature/issue-16-review-branch-commits-and-working-tree-c
Harden branch-and-worktree review isolation
2 parents 97a5e87 + bb20cc1 commit 14f7305

19 files changed

Lines changed: 3670 additions & 204 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ Key points:
169169

170170
### 1. Review
171171

172-
`code-converge` runs non-interactive `codex exec --output-schema <schema> --output-last-message <message> -` in the current directory. By default it resolves one review base in this order: an explicit review-base setting, the base of one open pull request for the current branch, `branch.<current>.gh-merge-base`, then exactly one remote default-branch ref. Provider discovery resolves its branch name against one remote-tracking ref and compares its commit SHA with the provider's advertised base SHA; a stale ref fails with an actionable fetch diagnostic. The resolved base SHA is pinned for every review in the run. Code-Converge computes the merge-base and prepares a private Git index from that tree plus the current worktree; this includes committed, staged, unstaged and untracked changes without modifying the real index or worktree. The exact private `GIT_INDEX_FILE` is supplied to the Codex process and forced into its spawned-tool environment for that invocation; the review instruction compares `git diff --cached` from the computed merge base. Ambiguous, missing or stale candidates fail with a diagnostic before Codex starts. Provider discovery through `gh` is optional; unavailable `gh` or authentication falls through to local Git sources. No implicit fetch, PR mutation or other remote mutation occurs.
172+
`code-converge` runs non-interactive `codex exec --output-schema <schema> --output-last-message <message> -` in the current directory. By default it resolves one review base in this order: an explicit review-base setting, the base of one open pull request for the current branch and its configured push/provider repository (or `origin` when Git's usual push-remote settings are absent), `branch.<current>.gh-merge-base`, then exactly one remote default-branch ref. Provider discovery verifies the PR head repository and branch against the current branch's provider identity, resolves the PR base branch against one remote-tracking ref and compares its commit SHA with the provider's advertised base SHA; an unverifiable head or stale base fails with an actionable diagnostic. The resolved base SHA is pinned for every review in the run. Code-Converge computes the merge-base and prepares a private Git index from that tree plus the current worktree; this includes committed, staged, unstaged and untracked changes without modifying the real index or worktree. A review-only Git helper applies that index only after confirming that a Git command targets the reviewed repository, while absolute Git paths, repository-creation commands, and commands targeting another repository retain their normal index. Code-Converge forces its wrapper-first `PATH` and neutral shell-startup settings through the per-review Codex shell policy, disables login-shell startup, and removes inherited Git repository/index/config transports and exported shell functions for that review. This prevents startup files or caller state from reordering `PATH`, replacing `git`, or redirecting Git away from the intended repository/index. The helper reads its private configuration from a sidecar file, so an `include_only` policy that allows `PATH` needs no extra helper variables; `GIT_INDEX_FILE` is not exported to Codex. All paths recorded in that sidecar must be valid UTF-8; unsupported Linux byte paths fail before the helper is created rather than being replaced during JSON encoding. Reviewed-root commands that explicitly enable Git split-index are rejected before they can create shared-index state outside the disposable command index. The review instruction compares `git diff --cached` from the computed merge base through the scoped helper. Ambiguous, missing or stale candidates fail with a diagnostic before Codex starts. Provider discovery through `gh` is optional; unavailable `gh` or authentication falls through to local Git sources. No implicit fetch, PR mutation or other remote mutation occurs.
173173

174174
`--review-base <ref>`, `CODE_CONVERGE_REVIEW_BASE` and `.code-converge/review-base` explicitly select the base using the normal configuration precedence. A branch already merged into the selected base has no committed delta but still reviews worktree changes; a fully clean run follows the existing clean/no-change path. It uses the model and reasoning effort resolved from the selected mode and any explicit stage overrides.
175175

‎cmd/code-converge/main.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,13 @@ import (
77
"syscall"
88

99
"github.com/dapi/code-converge/internal/app"
10+
"github.com/dapi/code-converge/internal/repository"
1011
)
1112

1213
func main() {
14+
if repository.IsScopedGitWrapperInvocation(os.Args[0]) {
15+
os.Exit(repository.RunScopedGitWrapper(os.Args[1:]))
16+
}
1317
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
1418
defer stop()
1519
os.Exit(app.App{}.Run(ctx, os.Args[1:]))

‎internal/app/app_test.go‎

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"os/exec"
1010
"path/filepath"
1111
"reflect"
12+
"strconv"
1213
"strings"
1314
"testing"
1415
"time"
@@ -19,6 +20,22 @@ import (
1920
"github.com/dapi/code-converge/internal/workflow"
2021
)
2122

23+
func TestMain(m *testing.M) {
24+
clearGitRepositoryEnvironment()
25+
os.Exit(m.Run())
26+
}
27+
28+
func clearGitRepositoryEnvironment() {
29+
for _, name := range []string{
30+
"GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE",
31+
"GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES",
32+
"GIT_NAMESPACE", "GIT_CEILING_DIRECTORIES",
33+
"GIT_DISCOVERY_ACROSS_FILESYSTEM", "GIT_IMPLICIT_WORK_TREE",
34+
} {
35+
_ = os.Unsetenv(name)
36+
}
37+
}
38+
2239
const cleanReviewJSONForApp = `{"findings":[],"overall_correctness":"patch is correct","overall_explanation":"no findings","overall_confidence_score":0.99}`
2340

2441
func testRepo(t *testing.T) (string, string) {
@@ -204,6 +221,14 @@ func (f *appFakeRunner) Run(_ context.Context, invocation runner.Invocation) (ru
204221
return f.status, f.statusErr
205222
case args == "symbolic-ref --quiet --short HEAD":
206223
return runner.Result{Stdout: "feature"}, nil
224+
case args == "config --get branch.feature.pushRemote", args == "config --get remote.pushDefault":
225+
return runner.Result{}, errors.New("not configured")
226+
case args == "config --get branch.feature.remote":
227+
return runner.Result{Stdout: "origin"}, nil
228+
case args == "remote get-url --push --all origin":
229+
return runner.Result{Stdout: "git@github.com:dapi/code-converge.git"}, nil
230+
case args == "remote get-url --all origin":
231+
return runner.Result{Stdout: "git@github.com:dapi/code-converge.git"}, nil
207232
case args == "config --get branch.feature.gh-merge-base":
208233
return runner.Result{}, errors.New("not configured")
209234
case args == "remote":
@@ -212,11 +237,11 @@ func (f *appFakeRunner) Run(_ context.Context, invocation runner.Invocation) (ru
212237
return runner.Result{Stdout: "refs/remotes/origin/main"}, nil
213238
case strings.HasPrefix(args, "rev-parse --verify "):
214239
return runner.Result{Stdout: "0123456789012345678901234567890123456789"}, nil
215-
case args == "rev-parse --git-path index":
240+
case strings.HasSuffix(args, "rev-parse --git-path index"):
216241
return runner.Result{Stdout: ".git/index"}, nil
217242
case strings.HasPrefix(args, "merge-base "):
218243
return runner.Result{Stdout: "abcdefabcdefabcdefabcdefabcdefabcdefabcd"}, nil
219-
case strings.HasPrefix(args, "read-tree ") || args == "add -A":
244+
case strings.HasPrefix(args, "read-tree ") || strings.HasSuffix(args, "-c core.splitIndex=false ls-files -v -z") || strings.HasSuffix(args, "add --sparse -A"):
220245
return runner.Result{}, nil
221246
}
222247
return f.status, f.statusErr
@@ -305,19 +330,27 @@ func TestAppWorkflowSuccessWithFakeRunner(t *testing.T) {
305330
break
306331
}
307332
}
308-
indexPath := ""
309-
if len(review.Env) == 1 {
310-
indexPath = strings.TrimPrefix(review.Env[0], "GIT_INDEX_FILE=")
333+
wrapperPath := ""
334+
for _, value := range review.Env {
335+
if strings.HasPrefix(value, "PATH=") {
336+
wrapperPath = strings.TrimPrefix(value, "PATH=")
337+
break
338+
}
311339
}
312340
reviewArgs := strings.Join(review.Args, " ")
313341
if len(review.Args) == 0 ||
314342
!strings.Contains(reviewArgs, " exec --output-schema ") ||
315343
!strings.Contains(reviewArgs, "--output-last-message") ||
316-
!strings.Contains(reviewArgs, "shell_environment_policy.set.GIT_INDEX_FILE=") ||
344+
!strings.Contains(reviewArgs, "shell_environment_policy.set.PATH="+strconv.Quote(wrapperPath)) ||
345+
!strings.Contains(reviewArgs, "shell_environment_policy.set.SHELL="+strconv.Quote("/bin/sh")) ||
346+
!strings.Contains(reviewArgs, "shell_environment_policy.set.ZDOTDIR=") ||
347+
!strings.Contains(reviewArgs, "shell_environment_policy.set.BASH_ENV="+strconv.Quote("")) ||
348+
!strings.Contains(reviewArgs, "shell_environment_policy.set.ENV="+strconv.Quote("")) ||
349+
!strings.Contains(reviewArgs, "allow_login_shell=false") ||
350+
strings.Contains(reviewArgs, "GIT_INDEX_FILE") ||
317351
!strings.Contains(review.Stdin, "0123456789012345678901234567890123456789") ||
318352
!strings.Contains(review.Stdin, "git diff --cached abcdefabcdefabcdefabcdefabcdefabcdefabcd") ||
319-
indexPath == "" ||
320-
!strings.Contains(review.Stdin, indexPath) {
353+
wrapperPath == "" {
321354
t.Fatalf("review was not bound to the resolved target: %#v", review)
322355
}
323356
}

‎internal/codex/adapter.go‎

Lines changed: 80 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"path/filepath"
1212
"strconv"
1313
"strings"
14+
"unicode/utf8"
1415

1516
"github.com/dapi/code-converge/internal/config"
1617
"github.com/dapi/code-converge/internal/repository"
@@ -85,7 +86,7 @@ func (a Adapter) Review(ctx context.Context) (ReviewResult, error) {
8586
if strings.TrimSpace(target.BaseCommit) == "" || strings.TrimSpace(target.MergeBase) == "" {
8687
return ReviewResult{}, errors.New("review target requires a selected base commit and merge base")
8788
}
88-
indexPath, err := reviewIndexPath(target.Env)
89+
args, err := scopedReviewArgs(a.Config, target)
8990
if err != nil {
9091
return ReviewResult{}, err
9192
}
@@ -101,16 +102,16 @@ func (a Adapter) Review(ctx context.Context) (ReviewResult, error) {
101102
return ReviewResult{}, fmt.Errorf("write review output schema: %w", err)
102103
}
103104

104-
args := append(
105-
modelArgs(a.Config.ReviewModel, a.Config.ReviewEffort),
106-
"-c", "shell_environment_policy.set.GIT_INDEX_FILE="+strconv.Quote(indexPath),
105+
args = append(
106+
args,
107107
"exec", "--output-schema", schemaPath, "--output-last-message", messagePath, "-",
108108
)
109109
if _, err := a.Runner.Run(ctx, runner.Invocation{
110-
Args: args,
111-
Env: target.Env,
112-
Stdin: reviewPrompt(target, indexPath),
113-
Output: a.output(),
110+
Args: args,
111+
Env: target.Env,
112+
UnsetEnv: target.UnsetEnv,
113+
Stdin: reviewPrompt(target),
114+
Output: a.output(),
114115
}); err != nil {
115116
return ReviewResult{}, err
116117
}
@@ -127,40 +128,93 @@ func (a Adapter) Review(ctx context.Context) (ReviewResult, error) {
127128
return review, nil
128129
}
129130

130-
func reviewIndexPath(env []string) (string, error) {
131-
var path string
132-
found := false
133-
for _, entry := range env {
134-
name, value, hasValue := strings.Cut(entry, "=")
135-
if name != "GIT_INDEX_FILE" {
136-
continue
131+
func scopedReviewArgs(configuration config.Config, target repository.ReviewTarget) ([]string, error) {
132+
required := []struct {
133+
name string
134+
nonEmpty bool
135+
}{
136+
{name: "PATH", nonEmpty: true},
137+
{name: "SHELL", nonEmpty: true},
138+
{name: "ZDOTDIR", nonEmpty: true},
139+
{name: "BASH_ENV"},
140+
{name: "ENV"},
141+
}
142+
args := modelArgs(configuration.ReviewModel, configuration.ReviewEffort)
143+
for _, item := range required {
144+
value, ok := environmentValue(target.Env, item.name)
145+
if !ok || item.nonEmpty && value == "" {
146+
return nil, fmt.Errorf("review scope did not provide required %s environment", item.name)
137147
}
138-
if found || !hasValue || strings.TrimSpace(value) == "" {
139-
return "", errors.New("review target requires exactly one non-empty GIT_INDEX_FILE")
148+
quoted, err := quoteTOMLString(value)
149+
if err != nil {
150+
return nil, fmt.Errorf("review scope %s environment: %w", item.name, err)
140151
}
141-
path = value
142-
found = true
152+
args = append(args, "-c", "shell_environment_policy.set."+item.name+"="+quoted)
143153
}
144-
if !found {
145-
return "", errors.New("review target requires exactly one non-empty GIT_INDEX_FILE")
154+
// A login shell can prepend a system Git directory after Codex applies PATH.
155+
// Disable it as a second layer after selecting a neutral non-login shell and
156+
// neutralizing user-controlled non-interactive startup files.
157+
args = append(args, "-c", "allow_login_shell=false")
158+
return args, nil
159+
}
160+
161+
func quoteTOMLString(value string) (string, error) {
162+
if !utf8.ValidString(value) {
163+
return "", errors.New("value is not valid UTF-8")
164+
}
165+
var quoted strings.Builder
166+
quoted.Grow(len(value) + 2)
167+
quoted.WriteByte('"')
168+
for _, character := range value {
169+
switch character {
170+
case '\b':
171+
quoted.WriteString(`\b`)
172+
case '\t':
173+
quoted.WriteString(`\t`)
174+
case '\n':
175+
quoted.WriteString(`\n`)
176+
case '\f':
177+
quoted.WriteString(`\f`)
178+
case '\r':
179+
quoted.WriteString(`\r`)
180+
case '"':
181+
quoted.WriteString(`\"`)
182+
case '\\':
183+
quoted.WriteString(`\\`)
184+
default:
185+
if character < 0x20 || character == 0x7f {
186+
fmt.Fprintf(&quoted, `\u%04X`, character)
187+
continue
188+
}
189+
quoted.WriteRune(character)
190+
}
191+
}
192+
quoted.WriteByte('"')
193+
return quoted.String(), nil
194+
}
195+
196+
func environmentValue(environment []string, name string) (string, bool) {
197+
prefix := name + "="
198+
for index := len(environment) - 1; index >= 0; index-- {
199+
if strings.HasPrefix(environment[index], prefix) {
200+
return strings.TrimPrefix(environment[index], prefix), true
201+
}
146202
}
147-
return path, nil
203+
return "", false
148204
}
149205

150-
func reviewPrompt(target repository.ReviewTarget, indexPath string) string {
206+
func reviewPrompt(target repository.ReviewTarget) string {
151207
return fmt.Sprintf(
152208
`Review the changes in the prepared private Git index.
153209
154210
Selected base commit: %s
155211
Merge base and comparison start: %s
156-
Private index path: %s
157212
158-
GIT_INDEX_FILE is set to the private index path for this process and for commands you run. Review the equivalent of git diff --cached %s so the comparison covers the merge-base-to-private-snapshot change. Inspect related files when needed, but do not modify the repository, the real index, or the worktree.
213+
A scoped Git helper exposes the private snapshot only to Git commands that target the reviewed repository. Review the equivalent of git diff --cached %s so the comparison covers the merge-base-to-private-snapshot change. Inspect related files when needed, but do not modify the repository, the real index, or the worktree.
159214
160215
Return actionable code-review findings. Use an empty findings array when there are none. Return only the JSON object required by the supplied output schema.`,
161216
target.BaseCommit,
162217
target.MergeBase,
163-
indexPath,
164218
target.MergeBase,
165219
)
166220
}

0 commit comments

Comments
 (0)