Skip to content

fix: audit sweep for security, billing, cost and structure - #60

Merged
hyochan merged 128 commits into
mainfrom
fix/audit-sweep
Nov 29, 2026
Merged

hyochan merged 128 commits into
mainfrom
fix/audit-sweep

Conversation

@hyochan

@hyochan hyochan commented Nov 29, 2026

Copy link
Copy Markdown
Member

Summary

A full audit of the repository, fixed in one pass: security boundaries, billing correctness, Convex cost, review reliability, dead code, structure and docs. Every area was reviewed independently afterwards, and every finding of that review is either fixed here or listed under "Not in this PR".

Security

  • Approvals: Gitdog approves a pull request only when its author has write access to the repository (checked with one GitHub call before the review is claimed). resolve and full review need a collaborator. Before this, an outside contributor could get an approval by prompt injection or by resolving Gitdog's own threads.
  • Spend by outsiders: issues, discussions, edits and follow-up mentions share the pull request command limits per repository and GitHub user (10 an hour, 40 a day, then a 24-hour pause). Bot authors are skipped, edits wait 90 seconds, a ticket is not answered twice for the same content, and the repository owner and trusted authors are exempt.
  • Replies: mentions are quieted except the author, the commenter answered and at most one maintainer; replies with other mentions, images or raw HTML wait for approval. Issue, discussion and comment text is delimited and marked untrusted in every prompt.
  • Access: organization installation owners are re-verified daily (and on organization/member events when the app subscribes to them); cached private file content is returned through an authenticated action instead of permanent storage URLs; project API keys are rate limited (60 requests a minute) and can no longer change approval gates or response styles; profiles are private; invitations expire after 14 days; maintainers come from push collaborators only.
  • Webhooks: the signature header is checked before the body is read, redelivered and out-of-order events are dropped, and malformed signed events are acknowledged instead of failing.
  • Keys and CI: provider keys saved under a rotated server key are erased; the CLI redacts every key shape the server accepts and confirms before sending a key to a custom backend. No pull request job receives the production Convex deploy key or the Firebase service account any more.

Billing

  • Unresolved usage holds are released after 7 days and shown on the Usage page, so they no longer block an account indefinitely.
  • Token packs are always credited; payment events that cannot be applied are kept for review (with a daily report and an admin resolve) instead of failing, while events that only need a retry still return an error so Lemon Squeezy retries.
  • Checkout refuses a duplicate Pro subscription, one in dunning, and one whose ended period is still settling.
  • Refunds are idempotent by payment log; payment log edits are note-only.
  • Free plan wording matches the trial-only plan from 2026-12-01; usage holds use the fallback model's weight after the Claude route ends; a Pro trial gives no entitlement.

Reviews

  • When Claude credit runs out, the rest of the run goes straight to the fallback model instead of asking Claude on every step.
  • Changed files up to 1 MB (for example a large lockfile) are reviewed around their diff instead of failing.
  • Public failure comments say why a review failed and whether retrying helps, from a stored failure kind.
  • The status comment is retried without posting duplicates; commands inside code blocks are ignored (CommonMark fences).
  • The trial is granted before a review catch-up checks the balance.

Convex cost

  • Pushes skip indexing while no assistant uses the index, unchanged file maps are no longer rewritten, several tree pages run per action, and old indexing logs are deleted.
  • The tickets page reads bounded pages instead of every ticket and action; admin and pull request queries use index ranges.
  • Idle recovery crons run as single mutations, two backstops run every 15 minutes, reservation cleanup keeps going while batches are full, the provider-slot poll backs off, and review records are written without reads.

Structure and cleanup

  • convex/pullRequests/workflow.ts (about 2,200 lines) is split into small modules around one review session object; generate and publish are split into scope, group, tally, proposal and publication modules. Failure messages are tied to their classification at compile time.
  • The retired embedding path is removed (billing, crons, publication, the OpenAI pass and the e2e checks), along with unreferenced Convex functions, modules, exports, about 95 unused translation keys per locale, and tests that exercised only in-file mocks.
  • The web app shows readable errors instead of redacted "Server Error" text, recovers from stale chunks after a deploy, confirms destructive actions, and translates the remaining labels and dates. Site copy leads with pull request reviews.
  • The CLI reports usage errors as JSON, exits non-zero when nothing happened, explains network, session and expired-token failures, and tolerates settings added by a newer backend. CLI 0.6.0.
  • Docs, .env.example and agent instructions match the code.

Deployment notes

  • Schema changes are additive (new tables, optional fields and indexes); bunx convex deploy --dry-run against production validates with no index removed.
  • CLI 0.5.x keeps working except gitdog index file, which now tells the user to update; publish CLI 0.6.0 after this deploys.
  • The preview workflow reads the development Convex URL from a repository variable VITE_CONVEX_DEV_URL, which must exist before preview builds run.

Not in this PR

  • Lemon Squeezy behaviour after a failed renewal recovers or a subscription is unpaused needs a test-mode run before changing how those periods are settled.
  • Admin tools to act on refund reviews beyond resolving them, and GitHub App event subscriptions for immediate owner checks.

Checks

bun run lint, bun run typecheck, bun run test (2,300 tests), bun run typecheck:cli, bun run test:cli (144), bun run check:api, bun run build, bun run format:check, and a production convex deploy --dry-run.

🤖 Generated with Claude Code

Remove the convex-preflight job, which ran the pull request's dependencies
with the production CONVEX_DEPLOY_KEY in scope, and pass the key only to the
deploy steps that call the Convex CLI instead of whole jobs.
…he cli

provider-keys set now asks before sending a key to a backend other than
Gitdog's default, and stops without --yes where it cannot prompt. Output
redaction covers every sk- token the server accepts as a key.
Rotating the expected encryption key left the old ciphertext in place, so a
leaked old server key could still decrypt it. A self-rescheduling follow-up
now blanks the ciphertext and iv of rows saved under any other key, only when
the recorded id is the configured key's. The rows stay, so owners are still
asked to enter their keys again.
Correct request timeouts, the convention examples that named files, tables
and helpers that do not exist, the project summary in CLAUDE.md, the test
command in AGENTS.md, the model routing line in the readme, the coverage-pass
cutoff and a removed debug panel in the GitHub App guide, and add the missing
CUSTOM_AUTH_SITE_URL and CLI reference entries.
The ticket list read every ticket of the user and every action of each listed ticket. It now stops one match past the requested page and reports hasMore instead of an exact total, reads status filters through an index, and counts only pending approvals. The pending approval list reads open tickets through an index and checks each for one pending action before loading the page.
The ticket and indexing log lists filtered createdAt after the index, so each later page scanned every newer log again. The cursor is now part of the index range. Log statistics summarize at most the newest 500 logs of the 30-day window and flag a partial result instead of reading up to 10,001 full logs and failing past that.
Five recovery crons were actions that ran a query every five minutes to learn there was nothing to do. They only read rows and schedule follow-up work, so each is now one internal mutation, and the queries and claim mutations they called are plain helpers inside that transaction. Restore-index retries are scheduled as their existing action instead of running inside the cron.
Stale index recovery and stalled disconnect cleanup only restart work that normally continues through its own scheduled watchdog or continuation, so a longer scan interval delays nothing a user waits on. Crons that drive retries, release quota or provider slots, revoke access, or unblock a visible reply stay at five minutes.
The hourly cleanup handled at most 100 expired and 100 retained reservations per run, so a backlog larger than that never drained and kept its stored result checkpoints. It now reschedules itself after a full batch, like the embedding reservation cleanup.
A request waiting for another request's provider slot re-ran the reservation mutation every two seconds, up to 45 times for a 90 second review wait. Polls now wait 2, 5, then 10 seconds, at most 11 for the same budget; the total wait is unchanged.
Nothing writes embeddingUsageReservations any more, so the settlement crons, the embedding usage writers, the admin reconciliation mutation, the batch cache trimmers and the unused embedding retry arguments had no work left. The table definition and historical tokenUsage literals stay in the schema.
getPendingByTicket, setUserFeedback, deleteByRepository (with its
deleteLearningsByRepository helper), updateLogStatus,
debugRepositoryIndexing, getPendingIndexing, getAllActiveRepositories,
getCompletedRepositories and markInstallationActiveAfterReconciliation
had no caller, cron, scheduler or CLI reference. The one test that only
exercised markInstallationActiveAfterReconciliation goes with it, and so
does markInstallationSuspended, which only that test called.
The structured issue-analysis workflow and its prompts, the error-analysis and follow-up prompt files, the issueFormatting barrel, UpgradeModal and useAuthGuard had no importer. A prompt-source test no longer reads the deleted issue-analysis prompt file.
OrganizationJsonLd, WebSiteJsonLd, chooseProject,
getRepositoryInstallationId, getEffectiveServiceFeeRate,
SETTLEMENT_FINGERPRINT_VERSION and the LegalEligibilityBlockOutcome type
had no references.
Six files imported nothing from convex/ or src/ and asserted against in-file mocks that mirrored the implementation. tokenLimits.test.ts keeps its pricing-constant checks and loses the block that tested a local copy of canPerformAction.
FREE_TIER_ENABLED and PAID_PROJECT_BILLING_ENABLED are not read anywhere.
95 keys in each of en, ko and ja had no literal or dynamic reference in src/, including the ones only the deleted UpgradeModal used. usageBalance.test.ts no longer reads four of them.
Only issue and discussion answers read the repository index. With both
assistants off, a default-branch push or the daily sync no longer starts a
generation; the push is recorded once and indexed when an assistant is
turned on. Owner-requested syncs, first connection and reactivation still
index.
A generation used to patch indexVersion on every repoFileMap row to tell
kept files from removed ones. The tree snapshot is now sorted in file-map
path order, so each page is compared with the stored maps of its path
range: unchanged rows are not written, and rows whose path left the tree
are marked and deleted by the existing cleanup. Once such a generation
completes, fileMapLayout tells readers that every stored map is current,
the way ragChunkLayout does for chunks. Trees that GitHub truncates are
not path-ordered and keep the previous restamping.
Every 40-file page used to end its action with a progress log, a heartbeat
patch on the repository and a scheduled continuation. A run now keeps
walking pages for up to 20 seconds, so those are paid once per run: an
unchanged repository is compared in a single action and its repository
document is no longer patched once per page.
repoIndexingLogs rows were kept for as long as a repository stayed
connected, although only the current generation's logs are shown. A
completing file generation now deletes the earlier ones in bounded
batches.
The hourly cache cleanup read up to 100 stale blobs and then ran one
mutation for each. One mutation now reads the batch, keeps the referenced
blobs and deletes the rest.
A clean review approved whoever wrote the pull request, so a fork author
could get a Gitdog approval by steering the review or by resolving its
threads with a command and asking for a follow-up.

- approve only when GitHub reports the author as OWNER, MEMBER or
  COLLABORATOR; anyone else gets the same clean review as a comment
- let only collaborators run the resolve command
The status comment was settled once. A brief GitHub or installation
failure left it saying "Reviewing" for good, and a comment a maintainer
deleted made every later settle throw.

- settle again up to three times with the backoff observe uses
- forget a deleted comment and post the outcome again only when a
  reader still waits on it
- carry the claimed daily failure notice into the retry
The fence pattern did not nest, so a command shown inside a four-backtick
block that held a three-backtick line still ran. A fence now closes only
on a fence of the same character and at least the same length, and
inline code spans are skipped as well.
Almost every failure became "Gitdog could not complete the review.
Comment review to try again", also when asking again could not help or
had to wait. A failed review now stores a typed reviewFailureKind,
computed from the error itself, and the status comment words each kind:

- nothing readable in the pull request, without a retry hint
- another task of the account still running, usage still being
  confirmed, too many batched reviews, an unverified balance and a
  GitHub rate limit, each with when to ask again

Reviews stored before this change keep their message-based wording.
@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Visit the preview URL for this PR (updated for commit adb928a):

https://codeyou-df251--pr60-fix-audit-sweep-vgosdfeb.web.app

(expires Sun, 06 Dec 2026 17:15:49 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 844dad9c62537d028cabc21008e4e2e4031ce4e5

@gitdogai gitdogai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

3 potential issues in d1b1dfe

139 of 270 changed files were not fully reviewed.

Not a merge approval. Tests were not run. Gitdog

Comment thread convex/repoIndexing/fileContent.ts Resolved
Comment thread convex/subscriptions/credit.ts Resolved
@hyochan

hyochan commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

@gitdogai review

@gitdogai gitdogai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

No issues found in adb928a

Reviewed the 14 files changed since d1b1dfe. 4 of 14 changed files were not fully reviewed.

Not a merge approval. Tests were not run. Gitdog

@hyochan
hyochan merged commit afc086c into main Nov 29, 2026
9 checks passed
@hyochan
hyochan deleted the fix/audit-sweep branch November 29, 2026 17:19
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.

1 participant