Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
257 changes: 247 additions & 10 deletions packages/opencode/src/altimate/review/ai-review.ts

Large diffs are not rendered by default.

39 changes: 33 additions & 6 deletions packages/opencode/src/altimate/review/ai-verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,16 @@ import type { Finding } from "./finding"
import { type AiReviewFile, type AiTokens, type BatchUsage, addUsage, aiTimeoutMs, streamUsage } from "./ai-review"
import { type ReviewRunner, scanDiffLines, walkDiffLines } from "./orchestrate"
import { readStreamStep, type StepToolCall } from "../llm/stream-text"
import { isCredentialPath } from "./credentials"

const log = Log.create({ service: "ai-verify" })

// The verifier refuses a file that may hold credentials: by name (its path or, for a rename, its
// old path; a working-tree symlink's target) on both sides of `read_file` and `compiled_sql` and in
// `grep_project` hits; by content (private keys, service-account keys) in `read_file`, `compiled_sql`
// and every file `grep_project` would show. The AI lane never gets such a file, nor one whose diff holds a key.
export { holdsCredentials, isCredentialPath } from "./credentials"

/** What the verifier may read: the PR's files, the engine, and the dbt project. */
export interface AiVerifyEvidence {
dialect?: string
Expand All @@ -41,6 +48,8 @@ export interface AiVerifyEvidence {
prBody?: string
/** Head-side line numbers each changed file adds (see `addedLinesByFile`). */
addedLines: Map<string, Set<number>>
/** Every file the PR changes, repo-relative, including tests and CI outside the dbt project. */
prFiles?: string[]
}

export type Decision = "keep" | "discard" | "summary"
Expand Down Expand Up @@ -382,12 +391,27 @@ export function hunkAround(diff: string | undefined, line?: number): string {
: text || "(the line is outside the diff)"
}

/** Most PR file paths listed in a verifier message. */
const PR_FILES_MAX = 40

/** The user message for one batch: the PR title and each candidate with its hunk. Not the whole file, not the grounding. */
export function buildVerifyMessage(
prTitle: string | undefined,
candidates: Array<{ id: string; finding: Finding; diff?: string }>,
prFiles: string[] = [],
): string {
const parts = [`PR: ${(prTitle ?? "(untitled)").slice(0, 200)}`, "", "Candidates:"]
const parts = [`PR: ${(prTitle ?? "(untitled)").slice(0, 200)}`]
// A test-coverage claim is checked against the PR's own test files, which may sit outside the dbt project.
if (prFiles.length && candidates.some((c) => c.finding.category === "test_coverage")) {
const shown = prFiles.slice(0, PR_FILES_MAX)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The verifier cannot discover changed files after the first 40 paths, so a test added at path 41+ can be missed by the test-gap check; add a bounded file-list tool or otherwise expose all paths to the verifier.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/review/ai-verify.ts, line 395:

<comment>The verifier cannot discover changed files after the first 40 paths, so a test added at path 41+ can be missed by the test-gap check; add a bounded file-list tool or otherwise expose all paths to the verifier.</comment>

<file context>
@@ -378,12 +380,27 @@ export function hunkAround(diff: string | undefined, line?: number): string {
+  const parts = [`PR: ${(prTitle ?? "(untitled)").slice(0, 200)}`]
+  // A test-coverage claim is checked against the PR's own test files, which may sit outside the dbt project.
+  if (prFiles.length && candidates.some((c) => c.finding.category === "test_coverage")) {
+    const shown = prFiles.slice(0, PR_FILES_MAX)
+    parts.push(
+      "",
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same as r4627044412; tracked.

parts.push(
"",
"Files this PR changes (read_file can open any of them):",
...shown.map((p) => `- ${p}`),
...(prFiles.length > shown.length ? [`- … and ${prFiles.length - shown.length} more`] : []),
)
}
parts.push("", "Candidates:")
for (const { id, finding: f, diff } of candidates) {
parts.push(
"",
Expand Down Expand Up @@ -784,8 +808,9 @@ export function verifierTools(
...ev.addedLines.keys(),
...graph.parents.map((p) => p.path),
...graph.downstream.map((d) => d.path),
...(ev.prFiles ?? []),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The verifier's read allowlist now includes every PR file, including paths the user excluded with exclude or rubric excludeGlobs and out-of-project files. prFiles comes from the unfiltered collected list in run.ts, so those contents can reach the model provider. Build prFiles from the reviewable set after exclusions, or filter the allowlist with the same exclusion rules.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/review/ai-verify.ts, line 783:

<comment>The verifier's read allowlist now includes every PR file, including paths the user excluded with `exclude` or rubric `excludeGlobs` and out-of-project files. `prFiles` comes from the unfiltered `collected` list in run.ts, so those contents can reach the model provider. Build `prFiles` from the reviewable set after exclusions, or filter the allowlist with the same exclusion rules.</comment>

<file context>
@@ -763,6 +780,7 @@ export function verifierTools(
       ...ev.addedLines.keys(),
       ...graph.parents.map((p) => p.path),
       ...graph.downstream.map((d) => d.path),
+      ...(ev.prFiles ?? []),
     ]),
   ]
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 31cb5c4: prFiles (the verifier's read allowlist and the test-gap list) now drops paths that match the user's exclude globs, plus build output and vendored paths (isExcludedPath). Changed files outside the dbt project stay readable on purpose (a Python test elsewhere in the repo is evidence for a test-gap claim), as OrchestrateInput.prFiles documents.

]),
]
].filter((p) => !isCredentialPath(p))

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.

[MAJOR] Credential check only covers the new path; renames and symlinks still reach the model

].filter((p) => !isCredentialPath(p))

The filter is applied to the name the PR shows, not to what is read for it. makeContentResolver maps a renamed file's new path to its old path for side: "old" (git.ts:131-134), and in working-tree mode safeReadInside follows an in-repo symlink (git.ts:105-121).

Reproduced with the real resolver on a temp repo:

  • git mv profiles.yml profiles.yml.example (the usual fix after committing credentials), then read_file("profiles.yml.example", side:"old") returns password: SECRET123. compiled_sql/equivalence old side use the same path (ctx.file.oldPath).
  • A changed docs/link.md -> ../profiles.yml, read with no head ref (working-tree mode), returns the file content. Git-ref mode only returns the link text.

With ALTIMATE_REVIEW_AI_VERIFY=1 the verifier is model-driven, so a prompt in the PR body or diff can request these reads. The invariant "credential files are never readable" does not hold.

Fix: check the resolved identity, not only the requested name. In the readFile/compiledSql wrappers in orchestrate.ts, refuse when isCredentialPath(oldPath) on the old side (pass the rename map in), and in safeReadInside callers refuse when the realpath target (relative to the root) is a credential path or the entry is a symlink. Add rename and symlink regression tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. The verifier wrappers now check the path actually read: on the old side readFile/compiledSql look up the renamed file's old path and refuse a credential one (orchestrate.ts:2635-2662, engine old SQL included), and safeReadInside refuses a symlink whose resolved target is a credential file (git.ts:121). Both of your repros are now regression tests on temp repos: "the old side of a renamed credential file is refused" and "working-tree mode never follows a symlink to a credential file" in review-ai-verify.test.ts.

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.

⚠️ Partially fixed — the old-side and symlink repros are both refused now (orchestrate.ts:2643-2668, git.ts:121), and the regression tests pass. The same rename still leaks on the other side: after git mv profiles.yml profiles.yml.example with no edit, read_file("profiles.yml.example") (new side) returns the password, because the new name passes the check and readPath only maps the old side. See the new inline comment.

/** A requested path inside the review scope, as the repo-relative path to read; a project-relative path resolves too. */
const resolve = (p: unknown): string | undefined => {
const want = String(p ?? "").replace(/^\.?\/+/, "")
Expand All @@ -799,11 +824,11 @@ export function verifierTools(
graph.parents.find((p) => p.name === name && (p.kind === "model" || p.kind === "snapshot"))?.path ??
graph.downstream.find((d) => d.name === name)?.path
const side = z.enum(["old", "new"]).optional().describe("old=base, new=head (default)")
const scope = NA("outside review scope (changed files, their dbt parents and direct downstream models only)")
const scope = NA("outside review scope (files the PR changes, their dbt parents and direct downstream models only)")

return {
read_file: {
description: "Up to 200 numbered lines of a changed file, its dbt parents or direct children.",
description: "Up to 200 numbered lines of any file the PR changes (tests and CI included), a dbt parent or direct child.",
input: z.object({
path: z.string(),
side,
Expand Down Expand Up @@ -920,8 +945,9 @@ export function verifierTools(
async run({ pattern, glob }) {
if (!ev.grepProject) return NA("project search unavailable")
if (String(pattern).length < 2) return NA("pattern needs at least 2 characters")
const hits = await ev.grepProject(String(pattern), glob as string | undefined)
if (!hits) return NA("the search failed (git error, timeout, or a glob outside the project); this is not evidence of absence")
const found = await ev.grepProject(String(pattern), glob as string | undefined)
if (!found) return NA("the search failed (git error, timeout, or a glob outside the project); this is not evidence of absence")
const hits = found.filter((h) => !isCredentialPath(h.path))

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.

[MINOR] Git-quoted filenames slip past the grep credential filter

const hits = found.filter((h) => !isCredentialPath(h.path))

grepFixedAt (git.ts:213) parses newline-delimited git grep output. For non-ASCII or special names git emits a quoted path ("models/caf\303\251/profiles.yml"); the trailing quote defeats the $-anchored regex, so the hit text is returned. Fix: use git grep -z and parse NUL-delimited names (or pass -c core.quotepath=false and unquote), then filter canonical paths. Add a non-ASCII path test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Switched grepFixedAt to git grep -z (git.ts:230), so paths come back unquoted and the credential filter sees the real name. The test "grepFixedAt returns canonical non-ASCII paths" covers a models/café/profiles.yml hit at a ref and in the working tree.

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.

✅ Fixed — git grep -z at git.ts:230 with NUL-delimited parsing. Reproduced with real grepFixedAt at a ref and in the working tree: models/café/profiles.yml comes back unquoted and is filtered; a newline in a directory name splits the row but the tail still carries the credential basename, so nothing slips through. Regression test at review-ai-verify.test.ts:1300 passes.

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.

[MINOR] The content guard is not applied to grep_project (or to diffs), and misses armored PGP keys

const hits = found.filter((h) => !isCredentialPath(h.path))

read_file refuses any file that holdsCredentials, but grep hits are only filtered by name. Reproduced with the real grepFixedAt: a tracked models/k.md holding a -----BEGIN RSA PRIVATE KEY----- block is refused by read_file, while grep_project({pattern: "MIIE"}) returns models/k.md:2: MIIEp.... Key body lines carry no header, so a few patterns (up to 50 hits of 300 characters) reconstruct the key. The same applies to the diff of a file whose sql was dropped by holdsCredentials (orchestrate.ts:2619-2628): the diff is still sent. Separately CREDENTIAL_CONTENT requires PRIVATE KEY-----, so -----BEGIN PGP PRIVATE KEY BLOCK----- is not matched (credentials.ts:29).

Fix: make grep_project skip any path whose whole content fails holdsCredentials (or drop hits next to a key header), screen diff with holdsCredentials when building aiFiles, and match PRIVATE KEY( BLOCK)?-----.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 140737c. I went with the whole-file check: the evidence grepProject drops every hit from a file that is credential-like or whose full head content holdsCredentials (orchestrate.ts:2681). It fails closed when the content can't be read. An AI file whose diff holds a key is no longer sent. One whose full text holds a key is still sent, but only as its diff (screened, orchestrate.ts:2631). CREDENTIAL_CONTENT now matches -----BEGIN (?:[A-Z0-9 ]* )?PRIVATE KEY(?: BLOCK)?----- (credentials.ts:39). Test: "key material is screened by content: grep hits, diffs and PGP armor". It uses the real grepFixedAt and checks that a key file's body lines don't appear in hits, that a macro whose diff adds a key header isn't sent, and that the PGP header is matched.

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.

⚠️ Partially fixed — grep_project is now screened by whole-file content: a tracked RSA models/k.md and a PGP-armored file return no hits for MIIE, hits on files whose content cannot be read are dropped, and PRIVATE KEY BLOCK is matched (credentials.ts:39). Diffs are only screened for the header: an edit more than 3 lines into a key body sends the diff with key body lines (sql dropped, diff kept). Filed as a new MINOR at orchestrate.ts:2634.

return hits.length ? hits.map((h) => `${h.path}:${h.line}: ${h.text}`).join("\n") : "no matches"
},
},
Expand Down Expand Up @@ -1176,6 +1202,7 @@ export async function runAiVerify(
finding: input.findings[i],
diff: fileByPath.get(input.findings[i].file)?.diff,
})),
ev.prFiles,
)
return { idx, ids, message }
})
Expand Down
44 changes: 44 additions & 0 deletions packages/opencode/src/altimate/review/credentials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Connection profiles, env files, package-registry, git, cloud, Docker and Kubernetes credential
// stores, service-account and OAuth client keys, key material and Terraform variables. Matched on the file name.
const CREDENTIAL_FILE = new RegExp(
"(^|/)(" +

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.

[MINOR] Name list still misses common credential stores

"profiles\\.ya?ml",

isCredentialPath is false for .aws/credentials, .docker/config.json, kubeconfig, secrets.yml/secrets.json, client_secret*.json, and dbt profile variants such as ci/dbt_profiles.yml, profiles-ci.yml and profiles.yml.example. grep_project takes a glob and reaches any tracked project file, and the AWS INI format also passes holdsCredentials, so a changed .aws/credentials is readable and greppable with the verifier on.

Fix: add \.aws/credentials, \.docker/config\.json, kubeconfig, secrets?\.(ya?ml|json), client_secret[^/]*\.json, and [^/]*profiles[^/]*\.ya?ml(\.[^/]*)?, with positive and negative table cases.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added \.aws/credentials, \.docker/config\.json, kubeconfig, secrets?\.(ya?ml|json) and client_secret[^/]*\.json in 140737c (credentials.ts:8-26). For profiles I narrowed your pattern to (dbt[_-]?)?profiles([._-][^/]*)?\.ya?ml(\.[^/]*)?. It covers ci/dbt_profiles.yml, profiles-ci.yml, profiles.yml.example and profiles.prod.yaml. It does not cover [^/]*profiles[^/]*, because that would also match a model's schema file such as models/marts/customer_profiles.yml and drop it from the AI lane. The positive and negative tables in the "credential files" describe block include those cases, plus models/schema.yml, dbt_project.yml and models/secrets_summary.sql as negatives.

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.

✅ Fixed — every name from the report is matched (.aws/credentials, .docker/config.json, kubeconfig, secrets.yml|json, client_secret*.json, dbt_profiles.yml, profiles-ci.yml, profiles.yml.example) in the positive table. The new profiles pattern also matches ordinary schema files such as models/profiles_users.yml, and a few other stores are still missed; filed as a new MINOR at credentials.ts:8.

[
// profiles.yml, dbt_profiles.yml, profiles-ci.yml, profiles.yml.example; not a model's
// schema file such as customer_profiles.yml
"(dbt[_-]?)?profiles([._-][^/]*)?\\.ya?ml(\\.[^/]*)?",

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.

[MINOR] Name list: schema files hidden, other credential stores still missed

"(dbt[_-]?)?profiles([._-][^/]*)?\\.ya?ml(\\.[^/]*)?",

All listed names from the earlier review are covered. Two follow-ups, checked with isCredentialPath:

  • False positives: models/profiles_users.yml, models/profiles_schema.yml, models/marts/profiles_daily.yml, models/secrets.yml now match, so a project with a profiles model silently loses its schema yml from the AI lane, the verifier and grep (an empty files list in runReview). The negative table only has customer_profiles.yml, which the (^|/) anchor already excluded.
  • Still false: .kube/config (the standard kubeconfig location), kubeconfig.yaml, .snowsql/config, .databrickscfg, .streamlit/secrets.toml, credentials.yml, terraform.tfstate, .htpasswd, .boto, .config/gcloud/application_default_credentials.json.

Fix: restrict the profiles_* variants to the project root / non-model dirs, or exempt files whose text parses as dbt schema yml (version: 2 with models:), and add profiles_users.yml to the negative table. Add \.kube/config, \.snowsql/config, \.databrickscfg, secrets?\.(ya?ml|json|toml), credentials\.ya?ml, [^/]+\.tfstate(\.backup)?, \.htpasswd to the positive table.

"\\.env[^/]*", // .env, .env.local, .env-prod, .envrc
"[^/]+\\.env", // prod.env
"\\.netrc",
"\\.pgpass",
"\\.npmrc",
"\\.pypirc",
"\\.git-credentials",
"id_(rsa|dsa|ecdsa|ed25519)",
"keyfile[^/]*\\.json",
"[^/]*service[^/]*account[^/]*\\.json",
"credentials[^/]*\\.json",
"\\.aws/credentials",
"\\.docker/config\\.json",
"kubeconfig",
"secrets?\\.(ya?ml|json)",
"client_secret[^/]*\\.json",
"[^/]+\\.(pem|key|p12|pfx|p8|tfvars|tfvars\\.json)",
].join("|") +
")$",
"i",
)

/**
* A path whose name says it may hold credentials. A changed file named so, now or before a
* rename, is not sent to the AI lane, and the verifier neither reads it (either side) nor shows its grep hits.
*/
export function isCredentialPath(path: string): boolean {
return CREDENTIAL_FILE.test(path)
}

const CREDENTIAL_CONTENT = /-----BEGIN (?:[A-Z0-9 ]* )?PRIVATE KEY(?: BLOCK)?-----|"type"\s*:\s*"service_account"/

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SUGGESTION: the content guard misses age/SOPS secret keys

CREDENTIAL_CONTENT covers PEM, OpenSSH and PGP armor, but not AGE-SECRET-KEY-1… — the key format SOPS-encrypted dbt vars/profiles use. A file with an innocuous name holding one still reaches read_file, compiled_sql and the AI lane, which is the case this guard exists for. One alternative is enough:

Suggested change
const CREDENTIAL_CONTENT = /-----BEGIN (?:[A-Z0-9 ]* )?PRIVATE KEY(?: BLOCK)?-----|"type"\s*:\s*"service_account"/
const CREDENTIAL_CONTENT = /-----BEGIN (?:[A-Z0-9 ]* )?PRIVATE KEY(?: BLOCK)?-----|AGE-SECRET-KEY-1[0-9A-Z]{10,}|"type"\s*:\s*"service_account"/


/** Text that carries a private key (PEM, OpenSSH or PGP armor) or a cloud service-account key, whatever the file is called. */
export function holdsCredentials(text: string): boolean {
return CREDENTIAL_CONTENT.test(text)
}
4 changes: 3 additions & 1 deletion packages/opencode/src/altimate/review/dbt-patterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -991,7 +991,9 @@ export function redundantJoinPredicates(sql: string): string[] {
} else if (rel) i += rel[0].length
const tail = /^\s+(?:as\s+)?(\w+)\s+on\b/i.exec(s.slice(i)) ?? /^\s+on\b/i.exec(s.slice(i))
if (!tail) {
joins.push({ preds: [], start: m.index!, end: i, inner, outer })
// A join with no ON (`cross join params as p`): step over its alias so the chain continues.
const bare = /^\s+(?:as\s+)?(?!(?:natural|inner|left|right|full|cross|outer|join|lateral|on|using|where|group|order|qualify|having|union|limit|window|select|from)\b)\w+\b/i.exec(s.slice(i))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: A join ... using (...) has no ON clause, but this change does not step over it, so the join chain still breaks there and a redundant predicate on the next join is missed. Let the bare-join match also consume a USING (...) list.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/review/dbt-patterns.ts, line 933:

<comment>A `join ... using (...)` has no ON clause, but this change does not step over it, so the join chain still breaks there and a redundant predicate on the next join is missed. Let the bare-join match also consume a `USING (...)` list.</comment>

<file context>
@@ -929,7 +929,9 @@ export function redundantJoinPredicates(sql: string): string[] {
     if (!tail) {
-      joins.push({ preds: [], start: m.index!, end: i, inner })
+      // A join with no ON (`cross join params as p`): step over its alias so the chain continues.
+      const bare = /^\s+(?:as\s+)?(?!(?:natural|inner|left|right|full|cross|outer|join|lateral|on|using|where|group|order|qualify|having|union|limit|window|select|from)\b)\w+\b/i.exec(s.slice(i))
+      joins.push({ preds: [], start: m.index!, end: i + (bare?.[0].length ?? 0), inner })
       continue
</file context>
Suggested change
const bare = /^\s+(?:as\s+)?(?!(?:natural|inner|left|right|full|cross|outer|join|lateral|on|using|where|group|order|qualify|having|union|limit|window|select|from)\b)\w+\b/i.exec(s.slice(i))
const bare = /^\s+(?:as\s+)?(?!(?:natural|inner|left|right|full|cross|outer|join|lateral|on|using|where|group|order|qualify|having|union|limit|window|select|from)\b)\w+\b|^\s+using\s*\([^)]*\)/i.exec(s.slice(i))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Follow-up: low priority, tracked. The result is a missed redundant predicate, never a false one.

joins.push({ preds: [], start: m.index!, end: i + (bare?.[0].length ?? 0), inner, outer })
continue
}
const fallback = rel?.[1].split(".").pop()?.toLowerCase()
Expand Down
8 changes: 8 additions & 0 deletions packages/opencode/src/altimate/review/diff-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,14 @@ export function partitionChangedFiles(
return { reviewable, dropped }
}

/** True when a path is build output / vendored or matches one of the user's exclude globs:
* files the review must not read, even outside the reviewable set. */
export function isExcludedPath(path: string, extraExcludeGlobs: string[] = []): boolean {
const p = norm(path)
if (SKIP_DIR_PATTERNS.some((re) => re.test(p)) || SKIP_FILE_PATTERNS.some((re) => re.test(p))) return true
return extraExcludeGlobs.some((g) => globToRegExp(g).test(p))
}

/** Filter changed files down to the reviewable set, with their dbt kind. */
export function filterChangedFiles(
files: ChangedFile[],
Expand Down
13 changes: 10 additions & 3 deletions packages/opencode/src/altimate/review/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { promisify } from "node:util"
import { promises as fs } from "node:fs"
import path from "node:path"
import type { ChangedFile } from "./diff-filter"
import { isCredentialPath } from "./credentials"

/**
* Git helpers for the review pipeline. Produces the ChangedFile[] for a PR
Expand Down Expand Up @@ -95,7 +96,8 @@ export async function collectChangedFiles(opts: CollectOptions): Promise<Changed
* Blocks the "tracked symlink escapes the root" class of attack — e.g. a
* `models/evil.sql → /etc/passwd` symlink that would otherwise leak external
* files into the review pipeline (coderabbit + cubic security review).
* Returns undefined when the target escapes, is missing, or realpath fails.
* Returns undefined when the target escapes, is a credential file (by its
* resolved name), is missing, or realpath fails.
*
* Exported for the compiled-SQL resolver in compiled.ts so both content
* paths go through the same containment check — cubic + kilo suggested
Expand All @@ -114,6 +116,9 @@ export async function safeReadInside(root: string, rel: string): Promise<string
// startsWith check so `/repo-backup` doesn't count as inside `/repo`.
const sep = path.sep
if (targetReal !== rootReal && !targetReal.startsWith(rootReal + sep)) return undefined
// Judge the file actually read: an in-repo symlink (`docs/link.md -> ../profiles.yml`)
// must not reach a credential file the requested name doesn't show.
if (isCredentialPath(path.relative(rootReal, targetReal).split(sep).join("/"))) return undefined
return await fs.readFile(targetReal, "utf8")
} catch {
return undefined
Expand Down Expand Up @@ -220,7 +225,9 @@ export async function grepFixedAt(
// No pathspec would search the whole repository.
if (!pathspecs.length) return undefined
const maxHits = opts.maxHits ?? 50
const args = ["grep", "-n", "-I", "-F", "--full-name", "-m", String(maxHits), "-e", pattern, ...(ref ? [ref] : []), "--"]
// -z: NUL after the path and line number, and paths unquoted (git otherwise
// C-quotes non-ASCII names, `"models/caf\303\251/x.yml"`), so callers see canonical paths.
const args = ["grep", "-z", "-n", "-I", "-F", "--full-name", "-m", String(maxHits), "-e", pattern, ...(ref ? [ref] : []), "--"]
args.push(...pathspecs.map((p) => `:(top)${p}`))
let out: string
let failed = false
Expand All @@ -235,7 +242,7 @@ export async function grepFixedAt(
const hits: Array<{ path: string; line: number; text: string }> = []
for (const row of out.split("\n")) {
const rest = ref && row.startsWith(ref + ":") ? row.slice(ref.length + 1) : row
const m = /^(.+?):(\d+):(.*)$/.exec(rest)
const m = /^([^\0]+)\0(\d+)\0(.*)$/.exec(rest)
if (!m) continue
hits.push({ path: m[1], line: Number(m[2]), text: m[3].slice(0, 300) })
if (hits.length >= maxHits) break
Expand Down
Loading
Loading