Skip to content

Feature/enhance git workflow - #635

Merged
pikann merged 11 commits into
masterfrom
feature/enhance-git-workflow
Oct 25, 2026
Merged

pikann merged 11 commits into
masterfrom
feature/enhance-git-workflow

Conversation

@pikann

@pikann pikann commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Moves Git integration into Paca core, independent of the platform: repositories, identities, change requests, webhook intake, agent triggers and audit now live in core, and a provider plugin (GitHub first) only adapts one platform to the Git Provider SPI (gitprovider.v1). Agents can read and review pull requests, comment, check issues and CI, and are started by Git events.

Design: docs/ai-agent/git-agent-workflow.md. SPI: docs/plugins/git-provider-spi.md. Companion PRs: Go SDK (plugin-sdk-go v0.4.0, SPI + conformance suite) and paca-plugin-github v0.5.0 (the provider).

What's in it

Core (services/api) — migration 000073 (all the Git tables in one migration)

  • Neutral domain and store: identities (shared per host, optional per agent), linked repositories, webhook endpoints, event inbox, change-request cache, task links, audit log, comment index, project settings, agent triggers, runs.
  • Provider plugins are found by the git-provider capability and called through internal-only /_git/<op> routes (never reachable from a browser).
  • Identity setup and access grants (installing an identity on a repository owner's account when a repository is linked, and right after an agent's own identity is created).
  • Credentials minted per call, narrowed to one repository and read or write, cached in memory for at most 30 s and never persisted.
  • Operations for agents: change requests (context, files, diff, threads), issues, comments, checks and logs (secrets masked), file read and code search, open/update change requests, comments, thread replies, reviews, labels, reviewers, assignees, check re-runs, merge. Core adds an attribution footer and idempotency keys, indexes what it posts, and audits every call.
  • Event router: turns mentions, review requests, labels, feedback on a pull request an agent opened, CI failures on one, and opt-in auto-review into agent runs. Guards: bots never start runs, minimum repository permission for the actor, pause switch, one run per agent and subject, caps on CI-failure runs. It shows run state on the platform (reaction + Paca / <agent> check) and finishes it when the conversation ends.
  • IAM: git:read, git:write, git:approve, git:merge (project) and git.identities:manage (workspace). Every route is gated in the router; approving and merging have their own routes so the gate decides who may approve. The Editor role template gets git:read and git:write.
  • Task endpoints: GET /projects/{id}/tasks/{taskId}/git (change requests with CI status, branches) and link/unlink/create-branch routes.
  • Plugin system: app.page extension point (used by the Git setup callback), plugin proxy refuses /_git, per-plugin random source for the WASM runtime.

MCP (apps/mcp)

  • 20 Git tools (change_request_get_context, review_submit, comment_post, checks_get_logs, …). Text from the platform is returned inside UNTRUSTED fences.
  • list_repositories, clone_repository, push_branch and the workspace_* / git_* tools use the core API. Git runs through a credential helper: remotes stay token-free and the credential is fetched per command, so nothing lands in .git/config, the environment or ps.

Web (apps/web)

  • Admin Git page (providers and identities), setup callback page, project Git settings tab (link repositories, request access, agent automation settings), agent Git tab (own identity, triggers), role editor entries for the Git actions.
  • Task detail Branches and Pull requests sections: link, create and unlink, with CI status per pull request.
  • 9 locales.

Behaviour changes

  • The old GitHub plugin's project integration (PAT connection, project settings tab, task PR/branch UI, MCP github_* tools) is removed with the plugin's 0.5.0 release. Nothing is migrated: a PAT cannot back a provider identity. Admins set up a GitHub App identity and relink repositories.
  • Agents need git:read and git:write in their project role to use the Git tools. Existing projects keep their role as written; add the actions to Editor (or to the agent's role).
  • Repository plugins are now recognised by the git-provider capability instead of repository.

Testing

  • Go: unit tests for the service, router, ops and handlers; Postgres store tests (PACA_TEST_PG_DSN); router gate tests for every new action (read, write, approve, merge, identities, task linking).
  • MCP and web: component and tool tests (bun run test in each).
  • Verified on the dev stack against a real GitHub App: setup, install, repository link, credentials, PR/diff/issue reads, an agent review, and the task detail sections. Writes were only tried on a dedicated test repository.

Not included

Path filters for auto-review, @bot stop, GitHub-login → Paca-member mapping, a second provider.

- Introduced deep-linking to settings tabs in the project settings page.
- Added documentation for new app.page extension point, allowing plugins to register full pages accessible via URL.
- Updated NavItem structure to support app.page alongside project.page and admin.page.
- Enhanced the FrontendManifest to include app.page in the NavItems.
- Provided examples and guidelines for implementing callback pages in plugins.
- Implemented Git identity management, allowing for shared and agent-specific identities.
- Added repository linking functionality, enabling projects to connect to Git repositories.
- Introduced webhook handling for Git events, including identity setup and access granting.
- Created database migrations for Git-related tables, including identities, repositories, and event handling.
- Developed IAM guards for Git actions, ensuring proper authorization for read and write operations.
- Added comprehensive tests for Git routing and authorization logic.
- Enhanced response handling for Git-related errors in the API.
- Add functionality to link and unlink change requests to tasks.
- Implement linking and unlinking of branches to tasks.
- Introduce new API endpoints for managing task-related Git operations.
- Enhance Git task response DTOs to include CI summary information.
- Add tests for new task Git functionalities, ensuring proper behavior and error handling.
- Update IAM guards to enforce permissions for task-related Git operations.

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

Important

This is a large, well-structured Git integration — the SPI boundary, per-command credential broker, tenancy scoping and route guards are solid. A few things are worth tightening before merge: the untrusted-text fences can be escaped (defeating the prompt-injection guard), a redaction gap can surface secrets to agents/logs, and the change-request upsert can regress a merged PR's cached state.

Reviewed changes

  • Backend Git service (service/git/*, new) — links repositories to projects, ingests webhooks into an event inbox, orchestrates agent runs (triggers, status, finalize), mints per-command credentials, and renders the agent prompt.
  • Domain + Postgres store (domain/git/*, git_repository.go, git_workflow_repository.go) — identity/repository/change-request/run persistence, queue claiming with FOR UPDATE SKIP LOCKED.
  • Migrations 000073–000076 — identities, repositories, webhook endpoints, event inbox, change requests, task links, comment index, project settings, agent triggers, runs.
  • HTTP — git_handler.go, git_ops_handler.go, and route registration in router.go (per-action guards for read/write/approve/merge/identities).
  • Provider SPI — platform/gitprovider/* (client + synced types/errors), plugin internal_call.go.
  • MCP workspace tools — credential broker/helper, git runner, workspace prepare/push, git-tools.ts/workspace-tools.ts/repo-tools.ts.
  • Web — git settings/identities/setup callback, task-git section/forms, agent git tab/triggers, plus i18n (11 locales), docs and Caddy config.

⚠️ SPIVersion is documented as enforced but no code checks it

spi_types.go states "core refuses a provider whose major version it does not speak", but nothing compares Info.SPIVersion to gitprovider.SPIVersion. PluginProviders.Provider/Describe/List (service/git/providers.go) build a client and call Describe without inspecting the version, so a future gitprovider.v2 provider would be driven by the v1 client and its changed field layouts decoded into accepted-but-wrong results (e.g. a zero Credential).

Technical details
# Enforce the provider SPI version at the resolve boundary

## Affected sites
- `services/api/internal/platform/gitprovider/spi_types.go:11-14` — the contract comment claims core refuses a mismatched major.
- `services/api/internal/service/git/providers.go:34-58` — `Provider`/`Describe` never read `info.SPIVersion`.

## Required outcome
- After `Describe`, compare the major component of `info.SPIVersion` against `gitprovider.SPIVersion` (`strings.Cut(v, ".")`) and return `CodeUnsupported` / `gitdom.ErrProviderUnavailable` on mismatch, so a version-skewed plugin fails loudly at the boundary instead of mid-operation.
- Add a test covering a mismatch (only `contract_test.go:69` references `SPIVersion` today).

## Open questions for the human
- Should the check live in `PluginProviders.Provider` (every call) or once at `Describe`/install time?

ℹ️ Concurrency and idempotency gaps in run launching and setup

Two read-then-write sequences can double-execute under concurrent requests or multiple API replicas. Neither is catastrophic with today's idempotent providers, but both are worth an atomic claim.

Technical details
# Atomic claims for run launch and identity setup completion

## Affected sites
- `services/api/internal/service/git/router.go` (`launch`, ~687-721) + `migrations/000076_add_git_workflow.sql:65` — the "one run per agent and subject" invariant is a read (`FindActiveRunForSubject`) then `CreateRun`, but the unique key is `(event_id, repository_id, agent_id)`. Two distinct events for the same `(repository, agent, subject)` processed concurrently both pass and create parallel runs (duplicate comments/statuses, `CIFailureCap` overshoot).
- `services/api/internal/service/git/setup.go` (`CompleteIdentitySetup`, ~159-226) — reads `CompletedAt`, invokes the provider, then marks complete. Two concurrent callbacks with the same `state` both call the provider's completion leg.

## Required outcome
- Add a partial unique index on `(repository_id, agent_id, subject_kind, subject_number) WHERE status IN ('queued','running')` (or an advisory lock keyed on the subject) so the second launch is rejected.
- Claim the setup session atomically, e.g. `UPDATE git_setup_sessions SET completed_at = NOW() WHERE state = $1 AND completed_at IS NULL RETURNING …`, before calling the provider.

ℹ️ list_repositories prints a raw clone_url

apps/mcp/src/tools/repo-tools.ts:216 emits Clone URL: ${repo.clone_url} to the agent. The storage/schema contract says clone_url is token-free, but this is the one place a credentialed URL supplied by a provider would be shown verbatim; every other git path runs it through stripCredentials. Wrap it (or scrubSecret) for consistency.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Comment thread apps/mcp/src/tools/git-tools.ts Resolved
Comment thread apps/mcp/src/git/workspace.ts Resolved
Comment thread apps/mcp/src/git/credential-broker.ts Resolved

@pullfrog pullfrog Bot 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 new issues in this revision — the delta is comments and refactors only. The findings from the previous review (prompt-fence escaping, redactSecrets boundary, change-request upsert state regression, webhook tracking, provider-message redaction, worktree slug, broker protocol, TaskInProject soft-delete, case-sensitive unique) remain open and unchanged; this commit does not touch them.

Reviewed changes (delta c927edb → 1feebbb0)

  • sync-git-spi.sh — header text changed from "copied" to "generated" in the synced files.
  • SPI types/errors — added doc comments to enum blocks and rewrote Err* comments from Name: to Name means.
  • domain/git/repository.go — Repository interface comment renamed to Store.
  • gitprovider/contract_test.go — added //nolint:exhaustive on the type-kind switch.
  • git_workflow_repository.go — r.gitRunRecord.domain()/c.gitCRRecord.domain() simplified to r.domain()/c.domain() (behaviour-equivalent).
  • prompt.go — the default trigger branch rewritten from if/else if/else to a switch.
  • git_handler.go — providerError comment corrected, plus a CodeInvalidSignature, CodeInternal case with no return (falls through to the same default as before).
  • prompt_test.go — assertion !(a < b && b < c) rewritten as a >= b || b >= c.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

- Exported `sanitizeSlug` function for broader usage.
- Improved text neutralization in `fence` function to prevent fence marker leakage.
- Added `DeleteInboxEvent` method to the repository interface to manage inbox events effectively.
- Introduced `ErrRunActive` error to handle cases of unfinished runs in the git workflow.
- Implemented database migration to enforce unique constraints on active runs and repository paths.
- Enhanced secret redaction in provider error messages to prevent sensitive information leakage.
- Added tests for new functionality and edge cases in the git service and provider handling.

@pullfrog pullfrog Bot 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 critical issues — the review-fix commit addresses all ten prior findings; two minor notes inline.

Reviewed changes (delta 1feebbb0 → a0f56a12)

  • Provider SPI version is enforced at the resolve boundary — PluginProviders.verify asks a provider for its SPI version once per installed plugin version and refuses a mismatched major; List filters on the same check.
  • Untrusted-text fences are unescapable — neutralize loops to a fixed point and plain sanitizes the provider values (logins, branches, paths, check/label names) embedded outside the fence, in both the Go prompt and the MCP tools.
  • Credential redaction fixed — dropped the leading \b so prefixed names like DB_PASSWORD= match, exported RedactSecrets, and applied it to provider error details.
  • Change-request cache no longer regresses — a review event preserves the cached state/draft/merged_at, and a merge records merged_at.
  • Webhook tracking is retryable — a failed cache update deletes the inbox row so a redelivery is reprocessed instead of dropped as a replay.
  • Soft-deleted tasks are excluded — TaskInProject and the task-git list queries require deleted_at IS NULL.
  • New DB invariants (migration 000077) — a partial unique index for one active run per agent and subject (surfaced as ErrRunActive) and a case-insensitive unique index on (project_id, provider_id, host, lower(full_path)).
  • Credential broker and repo listing hardened — the broker compares the request's scheme, list_repositories strips credentials from clone_url, and sanitizeSlug can no longer yield ./...

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Comment thread apps/mcp/src/tools/git-tools.ts Resolved

@pullfrog pullfrog Bot 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 new issues found.

Reviewed changes (delta a0f56a12 → f1f9cdc7)

  • neutralize is now a single linear pass — both apps/mcp/src/tools/git-tools.ts and prompt.go replace the fixed-point loop with <{3,}UNTRUSTED → <<UNTRUSTED then UNTRUSTED>{3,} → UNTRUSTED>>, so a long bracket run can no longer make it quadratic.
  • An empty plugin version no longer skips SPI verification — PluginProviders.verify reads v, seen := p.verified[name] and returns early only on seen && v == version, so a plugin installed with Version: "" is still checked against the provider's reported SPI major.
  • Both regressions are covered by tests — a 200k-bracket timing assertion in the MCP and Go neutralize tests, and TestPluginProviders_AnEmptyPluginVersionIsStillVerified exercising the empty-version path.

The one-pass neutraliser is sound: after the open pass every UNTRUSTED is preceded by at most two < (a replacement emits <<UNTRUSTED and cannot be preceded by another <), so the close pass cannot recreate an open marker, and its own output cannot form a close marker. Both prior inline notes are resolved.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

- Removed the repository plugin adapter documentation as it is no longer needed.
- Deleted spike scripts related to bot reviewer and credential helper as they are obsolete.
- Updated the Git provider SPI documentation to clarify integration details and conformance requirements.
- Enhanced database schema for Git integration:
  - Added unique constraints for case-insensitive repository paths.
  - Introduced new tables for managing Git setup and access sessions.
  - Implemented triggers for agent runs and Git workflows.
- Cleaned up migration scripts to remove deprecated tables and ensure data integrity.
- Updated Russian, Vietnamese, and Chinese localization files for Git-related features, adding detailed descriptions and instructions for users.
- Introduced identity_handle in GitRepository and related entities to facilitate @mentioning the bot serving each repository.
- Enhanced the Git API to return identity handles when listing project repositories.
- Improved documentation for Git agent workflows, clarifying setup steps and UI elements.
- Added tests to ensure that repositories correctly carry their bot's handle when listed.

@pullfrog pullfrog Bot 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 critical issues — the UI refactor and the new repository-handle lookup look sound. One documentation/implementation mismatch inline.

Reviewed changes (delta 01ffbb8d → 45d75d28)

  • Repositories now carry their bot handle — Repository.IdentityHandle (read-only, not stored) is populated by ListProjectRepositories with a second query joining git_identities, exposed as GitRepositoryResponse.identity_handle and surfaced in the web GitRepository type and as an @handle copy chip; covered by TestGitStore_ListedRepositoriesCarryTheirBotsHandle.
  • Project Git settings rebuilt as a guided page — GitSettings.tsx composes Repositories, Automation (locked until a repository is linked, responder warning, limits/pause folded into an advanced section) and Using it; the standalone GitWorkflowPanel is deleted.
  • Shared Git UI primitives — new components/git/git-ui.tsx (CopyChip, Section, EmptyState); the admin identities page, agent Git tab and triggers adopt them.
  • Agent triggers grouped, unsupported ones visible — AgentGitTriggers.tsx groups triggers into requests / follow-up / proactive and renders provider-unsupported triggers disabled with an explanation instead of hiding them.
  • i18n and docs — new keys across 9 locales; git-agent-workflow.md §11 rewritten.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Comment thread docs/ai-agent/git-agent-workflow.md Resolved
- Updated AgentGitTriggers to remove 'label' from the trigger kinds.
- Removed label-related usage instructions from GitSettings.
- Updated localization files to reflect the removal of label references in multiple languages.
- Adjusted Git API to exclude 'label' from trigger kinds and related logic.
- Modified Git agent workflow documentation to clarify available triggers.
- Updated database migration to remove 'label' from the git_agent_triggers table.
- Refactored tests to ensure labels do not trigger agent actions.

@pullfrog pullfrog Bot 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 critical issues — the label trigger is removed cleanly and consistently across the Go domain/router, the web types and the migration. Two user-facing text references it missed, inline.

Reviewed changes (delta 45d75d28 → 5f01c7b0)

  • label trigger removed end to end — dropped gitdom.TriggerLabel from entity.go/TriggerKinds, the EventLabel case in router.go's decide (unknown kinds now fall through to the default ignore), the ViaLabel branch in addressedTrigger, and the labelTarget helper; gitprovider.EventLabel/ViaLabel/TriggerLabel stay declared in the SPI but no longer start a run.
  • Web mirrors the change — GitTriggerKind no longer unions "label", AgentGitTriggers' Respond to requests group drops it, and GitSettings' Using it list loses its label form.
  • i18n — the project.git.triggerKinds.label and project.git.usage.label entries are deleted and the usage headline reworded from "Three ways" to "Two ways" across all nine locales.
  • Migration — the git_agent_triggers kind CHECK in 000073 no longer accepts 'label'; the router test is repurposed as TestRouter_LabelsDoNotStartRuns.
  • Docs — git-agent-workflow.md trigger tables now describe review-request/assignment as identity-addressed and note label events are SPI-only and never start a run.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot 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 new issues found.

Reviewed changes (delta 5f01c7b0 → 03506c4c)

  • label trigger restored end to end — despite the commit subject, this commit reverts the prior removal: gitdom.TriggerLabel is back in entity.go/TriggerKinds (on by default), the EventLabel case and labelTarget helper return to router.go (paca → responder, paca:<handle> → that agent, case-insensitive), addressedTrigger maps ViaLabel, prompt.go gains the label title and the event prompt already renders - Label added:, and the 000073 trigger-kind CHECK accepts 'label' again. TestRouter_LabelsNameAnAgent covers both forms plus an unrelated label.
  • Web and i18n re-align — GitTriggerKind unions "label" again, AgentGitTriggers' requests group and GitSettings' Using it list regain the label form, and triggerKinds.label / usage.label return across all nine locales with the usage headline back to "Three ways".
  • Dead UI and stale docs removed — git-ui.tsx drops the unused StepList/FeatureGrid (and the stepStatus admin i18n), and git-agent-workflow.md §11 is rewritten to the shipped empty-state UI; this resolves the earlier docs/implementation mismatch.
  • Docs — trigger tables and the webhook section now list label as a trigger and describe label events.

Both prior open threads (responder.help stale copy; §11 describing unshipped UI) are addressed by this commit and have been resolved. Verified locally: go test ./internal/service/git/... ./internal/domain/git/... passes, and biome check (2.4.12) is clean on the four touched web files.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot 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 new issues found.

Reviewed changes (delta 03506c4c → d1760a7d)

  • Linking a repository now needs the workspace action too — POST /projects/{id}/git/repositories requires git:write and git.identities:manage, so a project writer can no longer point agents at a repository another project's installation exposed. GitSettings gates the form on the same pair (canLink) and shows a new linkNeedsAdmin empty-state message across all nine locales.
  • A provider can no longer resolve a link to an identity core did not offer — LinkRepository checks res.Identity.ID is one of the offered candidates before it looks the identity up or creates the repository.
  • Webhook intake refuses unknown endpoints before buffering — ReceiveWebhook calls the new CheckWebhookEndpoint (404 for an unknown or not-yet-configured key) before reading up to maxGitWebhookBody, and the public route gains a per-IP rate limit (60 × AuthRateLimit).
  • Cached credential minting is audited — the cache-hit path in MintCredential now records a credential.mint audit row with a (cached) detail, so every issue is logged.
  • Docs and tests — git-agent-workflow.md records the new link permission (permissions table, §11, limitations); new Go tests cover the combined gate, the unoffered-identity rejection, CheckWebhookEndpoint, and the cached-mint audit.

Verified locally: go build and go test ./internal/service/git/... ./internal/domain/git/... ./internal/transport/http/router/... pass.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pikann
pikann merged commit 2cde72b into master Oct 25, 2026
16 checks passed
@pikann
pikann deleted the feature/enhance-git-workflow branch October 25, 2026 11:34
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