* feat(ga-p9iuv.22): add shared tracker proxy storage seam
* fix(ga-p9iuv.22): preserve tracker storage capabilities safely
* test(ga-p9iuv.22): cover tracker adapter label semantics
* test(ga-p9iuv.22): harden tracker adapter contracts
* fix(ga-p9iuv.22): reject invalid proxied tracker stores
* feat(ga-p9iuv.1): route Linear and Jira front doors through proxy store
* test(ga-p9iuv.1): exercise tracker mutations through UOW store
* fix(ga-p9iuv.1): preserve proxied Linear endpoint config
* test(ga-p9iuv.1): cover proxied Linear endpoint and direct config
* feat(ga-p9iuv.19): add typed proxied capability matrix
* feat(proxy): enforce typed capability matrix before provider
* test(proxy): cover command capability rows and claim caps
* test(proxy): check capability rows across topologies
* fix(proxy): validate capabilities before workspace side effects
* fix(proxy): refuse ready claim max rows caps
* feat(proxy): add shared maintenance capability policy
* fix(proxy): key maintenance refusals by command path
* test(proxy): cover nested maintenance refusals
* fix(proxy): enumerate nested maintenance command paths
* fix(proxy): refine compact and nested maintenance policy
* test(proxy): prove maintenance refusals preserve files
* fix(proxy): cover admin and remote maintenance refusals
* fix(proxy): refuse doctor before store initialization
* test(proxy): define history capability command matrix
* fix(proxy): wire history capability refusals to front door
* fix(proxy): refuse top-level sync history path
* fix(proxy): preserve maintenance refusal codes
* feat(proxy): classify history as supported UOW API
* feat(proxy): classify transform capability paths
* test(proxy): harden transform capability matrix
* fix(proxy): drive transform validation from exact rows
* fix(proxy): drive transform matrix from normalized flags
* fix(proxy): bound external backend dials per attempt
* test(proxy): cover bounded blocked backend dial
* fix(proxy): make transform capability policy row-driven
* fix(proxy): make transform capability policy row-driven
* fix(proxy): classify formula swarm and merge-slot refusals
* test(proxy): enforce workflow refusal contract
* fix(proxy): classify Dolt remote history boundaries
* test(proxy): enforce history refusal contract
* test(proxy): cover canceled backend dial cleanup
* test(proxy): cover real TCP blackhole cancellation
* test(proxy): cover external transport lifecycle matrix
* test(proxy): assert stable dial failure diagnostics
* test(proxy): add outage reconnect acceptance matrix
* test(proxy): make unix outage bridge restartable
* test(proxy): bound outage subprocess cleanup
* test(proxy): cover upstream restart with retained endpoint bridge
* test(proxy): stabilize managed-local outage contract
* fix(proxy): retire managed proxy when backend exits
* test(proxy): accept managed child retirement restart
* test(proxy): cover workflow refusals at bd front door
* test(proxy): cover history VC front doors
* test(proxy): pass valid workflow refusal arguments
* test(proxy): assert text and json refusal contracts
* test(proxy): assert exact workflow refusal codes
* test(proxy): guard refusal issue-row stability
* fix(proxy): expose non-mutating capability refusals
* test(proxy): match stable refusal text
* test(proxy): compare refusal artifact snapshots
* test(proxy): assert exact refusal messages
* test(proxy): retain direct workflow behavior
* test(proxy): match nested refusal messages
* test(proxy): cover direct-only front-door refusals
* test(proxy): provide valid direct-only command args
* fix(migrate): repair missing proxied sidecar on reentry
* fix: checkpoint Dolt mode migrations for safe retry
* fix: harden migration journal topology and retries
* fix: fsync migration journal removal
* fix: fail on migration journal directory sync errors
* fix: reject external ownership in every migration phase
* fix: enforce canonical shared migration topology
* fix: enforce live migration topology
* test: add migration front-door and topology regressions
* fix: require physical Dolt roots for migration
* test: strengthen migration front-door contracts
* fix: reject missing or invalid Dolt migration roots
* fix: keep shared migration dry-runs side-effect free
* fix: require Dolt repository identity for migrations
* fix: validate Dolt repository identity metadata
* fix: require typed Dolt repo state identity
* test: expand migration front-door CRUD assertions
* test: make migration JSON dry-run front-door safe
* test: sanitize Dolt environment for migration front door
* test: use cgo binary for migration front door
* test: omit empty Dolt overrides in migration front door
* test: isolate migration front door from test mode
* test: isolate home for migration front door
* test: stop supervised Dolt before reverse migration
* fix: reject empty Dolt head refs
* test: harden migration topology invariants
* test: harden external and shared topology refusals
* test: snapshot migration refusal artifacts
* test: cover external migration refusal phases
* fix: refuse stale proxied sidecars during migration
* test: strengthen migration artifact and external front door checks
* feat: type external migration refusals
* test: assert external refusal starts no proxy
* fix: validate migration journal sidecar topology
* fix: make sidecar recovery phase aware
* fix: honor persisted shared topology during migration
* test: exercise external journal migration front door matrix
* test(tracker): add shared conformance harness
* test: harden external migration matrix fixtures
* test: preserve durable dolt gate lock in matrix
* test: preseed gate lock for refusal matrix
* test: cover malformed migration state front door
* fix: type malformed migration config refusals
* fix: type migration preflight state errors
* test: separate migration JSON stdout from warnings
* test: reach typed malformed journal refusal
* test: assert migration retry phase and idempotence
* test: cover shared migration checkpoint retries
* fix: make reverse migration idempotent without sidecar
* test: cover proxied to shared retries
* fix: derive shared topology from persisted YAML
* fix: validate shared migration no-op state
* fix: allow completed proxied shared no-op
* fix: validate forward proxied no-op sidecar
* test: reject bad already-proxied sidecars
* fix: reject stale proxy controls on no-op
* fix: fail closed on malformed migration workspace yaml
* test: pin migration yaml topology precedence
* Cover forward migration no-op ownership refusals (ga-p9iuv.26.5.2)
Agent-Signature: unknown-model/unknown-reasoning
* Strengthen migration retry sentinel coverage (ga-p9iuv.26.1)
Agent-Signature: unknown-model/unknown-reasoning
* Expand migration fault retry artifact coverage (ga-p9iuv.26.1)
Agent-Signature: unknown-model/unknown-reasoning
* Add reverse migration frontdoor fault matrix (ga-p9iuv.26.1.1)
Agent-Signature: unknown-model/unknown-reasoning
* test: cover shared migration frontdoor fault matrices
* test: strengthen direct migration matrix assertions
* test: preserve migration dependency edges
* test: assert exact migration dependency edges
* test: parse migration dependency edges from batch list
* test: fix shared migration matrix compile
* test: verify shared dependencies before shutdown
* test(proxy): cover history remote front-door topology matrix
* docs: define direct-local ownership handoff contract
* fix(ci): repair pre-review CI failures on proxy parity branch
Five PR-introduced failures across the docs, PR Core, and Proxied Dolt Cmd
lanes. Each fix is scoped to the evidenced defect.
- test/docsync: TestEveryDocsPageIsPublished flagged
docs/architecture/ownership-handoff-contract.md as unpublished. It is an
internal Beads/Gas City handoff contract with no Mintlify frontmatter and
no inbound links, so move it to engdocs/design/ beside its peers rather
than publishing it.
- cmd/bd: TestProxyWorkflowRefusalContractAndNoMutation asserted on
commandDidWrite, a process-wide atomic latch set by 71 non-test sites and
never reset, so it reported an earlier test's write. Baseline and restore
it around the assertion, matching the save/reset/restore idiom already
used in proxied_lookup_failure_test.go and readonly_policy_test.go.
- cmd/bd: the new pre-provider gate short-circuited compact.go's refusal
with new wording, breaking TestProxiedServerCompactDolt/non_dolt_mode_-
rejected in an unchanged test. Restore the long-standing message; the
proxy.compact.unsupported code is unchanged.
- internal/storage/dbproxy/proxy: the unix subtests bound sockets under
t.TempDir(), whose embedded test name overflows macOS's ~104-byte
sun_path limit ("bind: invalid argument"). Add unixSocketPath() to place
them in a short temp dir.
- cmd/bd: migration topology compared recorded and canonical Dolt roots
lexically, so macOS's /var -> /private/var symlink made equivalent paths
compare unequal. Add sameMigrationRoot(), mirroring the existing
resolveExistingPrefix idiom in cmd/bd/doctor/git.go.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(review): address blocker and major findings from adopt-pr review
Maintainer review fixup for the proxy parity branch, iterations 1-2.
Blockers and majors from the review synthesis and quality scorecard.
Blockers:
- cmd/bd/migrate_dolt_mode.go: resuming from migratePrepared rebuilt the
migration plan from the current argv instead of replaying the recorded
one. A resume that omitted or changed --idle-timeout wrote a sidecar the
target_configured check then rejected, and because that check runs only
after the phase advances past migratePrepared, the block never ran again
— the workspace stayed wedged in proxied-server mode with no in-tool
recovery. Replay j.Sidecar and warn when the supplied value is ignored.
- internal/tracker/store.go: NewStore double-wrapped already-adapted values.
directStore embeds the storage.Storage interface, so *directStore also
satisfies storage.Storage and was re-wrapped as
&directStore{Storage: &directStore{...}}; the inner value can never
satisfy storage.IssueLifecycleStore, which silently degraded
ApplyIssueUpdate to a bare UpdateIssue — no labels, no lifecycle
transaction. Match the tracker's own adapters by concrete type first.
Testing value.(Store) first, as the review suggested, does not work:
storage.Storage is a strict superset of Store, so a raw direct store
satisfies Store too and would be returned un-adapted, relocating the same
bug. The branch order is documented at the call site.
Majors:
- internal/tracker/store.go: directStore.ApplyIssueUpdate now calls
syncIssueLabels, which normalizes both label sets (trim, drop empty) and
restores the semantics the pull path had before this seam moved behind
ApplyIssueUpdate. The un-normalized local copy churned remove+add on
whitespace-only differences and let an empty label reach AddLabel; it is
deleted rather than left as a second, divergent implementation.
- Both regressions were invisible to the suite. Adds
TestNewEngineKeepsDirectStoreAdaptationIntact, TestNewStoreIsIdempotent,
TestDirectStoreApplyIssueUpdateNormalizesLabels, and
TestMigrateToProxiedServer_ResumeReplaysRecordedIdleTimeout (changed /
omitted / never subtests, each also asserting the reverse-migration escape
hatch still recovers). All four were verified to fail against the
pre-fix production code with the predicted symptoms.
Non-gating follow-ups from the scorecard, fixed while nearby:
- cmd/bd/proxy_capability.go: treat ProxyOutcomeNA as "this command has no
such flag" rather than a refusal, so an assert on an N/A row cannot return
a non-nil error carrying an empty message.
- cmd/bd/errors.go: emit the rule's real Mutates value in the JSON refusal
envelope instead of a hardcoded false.
- cmd/bd/main.go: the doctor pre-provider check returned unconditionally,
so a nil result (every doctor subcommand) skipped the legacy-store guard
and autocommit-mode resolution that other skipsStoreInit commands run.
Return only on a real refusal.
- internal/tracker/engine.go: type NewEngine's store parameter as Store so
the seam names its contract, and drop the now-dead applyPullIssueUpdate.
- CHANGELOG.md: record the proxied `bd ready --claim` row-cap refusal, which
was a behavior change shipped without a release note.
Iteration 2 -- gating major (uowStore/directStore external_ref divergence):
- internal/tracker/uow_store.go: GetIssueByExternalRef resolved through a
single merged search over both storage planes, which has no plane
preference: it is a UNION ALL ordered by content and terminating in
`id ASC`, so one external_ref present on both planes resolved to whichever
row's id sorted first. The direct backend is explicitly issues-first --
issueops.GetIssueByExternalRefInTx queries `issues` and falls through to
`wisps` only on sql.ErrNoRows, and says why ("so that pushed ephemeral
beads are found during pull dedup"). The consumer is the pull dedup, which
updates whatever row comes back, so the divergence was a silent write to
the wrong local bead under --proxied-server only. Query the issues plane
first via SkipWisps, then fall back.
The fallback is the merged search rather than the review's literal
Ephemeral=true: that filter contributes an `ephemeral = 1` predicate the
direct backend's `SELECT id FROM wisps WHERE external_ref = ?` does not
have, and wisp-plane rows legitimately carry ephemeral=0 (NoHistory beads;
see types.IssueFilter.EphemeralTier). Taking it literally would have traded
one divergence for a narrower one. Verified: implementing the prescription
fails the ephemeral_flag_clear subtest below.
- internal/tracker/uow_store_engine_test.go: the engine fake now models plane
routing (SkipWisps / Ephemeral / merged) instead of one flat map, so the
contract is expressible at all. Adds
TestUOWStoreGetIssueByExternalRefPrefersIssuePlane, whose wisp id sorts
first so "first merged hit" fails it, and
TestUOWStoreGetIssueByExternalRefFallsBackToWispPlane over both ephemeral
values. Verified to fail against the pre-fix uow_store.go.
- internal/tracker/conformance: the shared suite gains a Wisps plane and
external_ref_resolution_prefers_issue_plane, so this is a contract both
backends are held to rather than one adapter's unit test.
Iteration 2 -- non-gating follow-ups from the scorecard:
- cmd/bd/migrate_dolt_mode.go: scope the migratePrepared sidecar-equivalence
check in runMigrateFromProxiedServer to reverse journals. A forward journal
at that phase records the sidecar it is about to write, so a crash in the
pre-write window leaves none on disk -- the correct state -- and the
unscoped check refused the documented escape hatch by naming a missing
file, stranding the workspace. Tested against TargetMode's forward value so
the guard stays live for both reverse targets, "server" and
"shared-server". Adds
TestMigrateFromProxiedServer_ForwardJournalAtPreparedIsNotSidecarRefused,
verified to fail against the unscoped guard.
- cmd/bd/linear.go: buildLinearClientAPIOnly returned the OAuth client inline
and never reached the WithEndpoint block, so a configured
linear.api_endpoint was honored for an API key and ignored for OAuth. Hoist
the endpoint application after the branch, as Tracker.Init does, and add
the OAuth mirror of the existing endpoint test.
- cmd/bd/ready_max_rows_proxied_test.go: pin the proxied --max-rows refusal
on `bd ready --claim`. It lives in RunE above the dispatch and nothing
below it can enforce a cap, but the existing coverage all sits below it.
Covers both cap sources (--max-rows and BEADS_MAX_ROWS) and the negative
case that the refusal is conditioned on a live cap, not on --claim.
- engdocs/design/ownership-handoff-contract.md: trim the trailing blank line
at EOF flagged by `git diff --check`.
Iteration 3 -- non-gating residual on the iteration-2 fix:
- internal/tracker/uow_store.go: the issues-first fix above split one logical
lookup across two read transactions. uow.RunTxRead opens a fresh unit of
work per call, so calling s.SearchIssues twice left the wisp fallback's
premise -- "the issues plane is already known empty" -- without a shared
snapshot: a concurrent same-ref insert into the issues plane landing between
the two reads could let the merged fallback return the wisp, re-creating the
wrong-row write that ordering exists to prevent. The consumer is the pull
dedup loop, so it runs per imported issue. Both plane reads now share a
single RunTxRead, which is also the shape the direct backend uses (both
planes inside one withReadTx). Plane ordering is unchanged.
- internal/tracker/uow_store_engine_test.go: the engine fake counts the units
of work it hands out, and
TestUOWStoreGetIssueByExternalRefUsesOneReadTransaction pins that count at 1
across the two paths that actually perform both reads -- the wisp fallback
and the miss. An issues-plane hit short-circuits after one read and would
pass either way, so it is not a case. Verified to fail against the
two-transaction version with "opened 2, want 1".
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
624 lines
18 KiB
Go
624 lines
18 KiB
Go
package gitlab
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/tracker"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
func init() {
|
|
tracker.Register("gitlab", func() tracker.IssueTracker {
|
|
return &Tracker{}
|
|
})
|
|
}
|
|
|
|
// issueIIDPattern matches GitLab issue URLs: .../issues/42 or .../work_items/42
|
|
var issueIIDPattern = regexp.MustCompile(`/(?:issues|work_items)/(\d+)`)
|
|
|
|
// glShorthandPattern matches the "gitlab:{digits}" shorthand produced by BuildExternalRef
|
|
// when a full URL is unavailable.
|
|
var glShorthandPattern = regexp.MustCompile(`^gitlab:([1-9]\d*)$`)
|
|
|
|
// milestoneIDPattern matches GitLab milestone URLs: .../-/milestones/5
|
|
var milestoneIDPattern = regexp.MustCompile(`/-/milestones/(\d+)`)
|
|
|
|
const gitLabMilestoneIdentifierPrefix = "milestone:"
|
|
|
|
// Tracker implements tracker.IssueTracker for GitLab.
|
|
type Tracker struct {
|
|
client *Client
|
|
config *MappingConfig
|
|
store tracker.Store
|
|
filter *IssueFilter // Optional filters for issue fetching
|
|
projectPath string // GitLab project path (e.g., "socwave/socwave") for GraphQL
|
|
}
|
|
|
|
func (t *Tracker) Name() string { return "gitlab" }
|
|
func (t *Tracker) DisplayName() string { return "GitLab" }
|
|
func (t *Tracker) ConfigPrefix() string { return "gitlab" }
|
|
|
|
// GitLabClient returns the underlying GitLab API client.
|
|
func (t *Tracker) GitLabClient() *Client { return t.client }
|
|
|
|
func (t *Tracker) Init(ctx context.Context, store tracker.Store) error {
|
|
t.store = store
|
|
|
|
token, err := t.getConfig(ctx, "gitlab.token", "GITLAB_TOKEN")
|
|
if err != nil || token == "" {
|
|
return fmt.Errorf("GitLab token not configured (set gitlab.token or GITLAB_TOKEN)")
|
|
}
|
|
|
|
baseURL, _ := t.getConfig(ctx, "gitlab.url", "GITLAB_URL")
|
|
if baseURL == "" {
|
|
baseURL = "https://gitlab.com"
|
|
}
|
|
|
|
projectID, _ := t.getConfig(ctx, "gitlab.project_id", "GITLAB_PROJECT_ID")
|
|
groupID, _ := t.getConfig(ctx, "gitlab.group_id", "GITLAB_GROUP_ID")
|
|
defaultProjectID, _ := t.getConfig(ctx, "gitlab.default_project_id", "GITLAB_DEFAULT_PROJECT_ID")
|
|
|
|
// When group_id is set, default_project_id is used for creating issues.
|
|
// When group_id is not set, project_id is required.
|
|
if groupID == "" && projectID == "" {
|
|
return fmt.Errorf("GitLab project ID not configured (set gitlab.project_id or GITLAB_PROJECT_ID)")
|
|
}
|
|
|
|
// For group mode, use default_project_id as the project for creating issues.
|
|
// If default_project_id is not set, fall back to project_id.
|
|
if groupID != "" && projectID == "" {
|
|
if defaultProjectID != "" {
|
|
projectID = defaultProjectID
|
|
}
|
|
}
|
|
|
|
t.client = NewClient(token, baseURL, projectID)
|
|
if groupID != "" {
|
|
t.client = t.client.WithGroupID(groupID)
|
|
}
|
|
t.config = DefaultMappingConfig()
|
|
|
|
// Load project path for GraphQL (e.g., "socwave/socwave")
|
|
t.projectPath, _ = t.getConfig(ctx, "gitlab.project_path", "GITLAB_PROJECT_PATH")
|
|
|
|
// Load optional filter config
|
|
t.filter = t.loadFilterConfig(ctx)
|
|
|
|
return nil
|
|
}
|
|
|
|
// loadFilterConfig reads filter configuration from store/env.
|
|
// Returns nil if no filters are configured.
|
|
func (t *Tracker) loadFilterConfig(ctx context.Context) *IssueFilter {
|
|
labels, _ := t.getConfig(ctx, "gitlab.filter_labels", "GITLAB_FILTER_LABELS")
|
|
projectStr, _ := t.getConfig(ctx, "gitlab.filter_project", "GITLAB_FILTER_PROJECT")
|
|
milestone, _ := t.getConfig(ctx, "gitlab.filter_milestone", "GITLAB_FILTER_MILESTONE")
|
|
assignee, _ := t.getConfig(ctx, "gitlab.filter_assignee", "GITLAB_FILTER_ASSIGNEE")
|
|
|
|
if labels == "" && projectStr == "" && milestone == "" && assignee == "" {
|
|
return nil
|
|
}
|
|
|
|
filter := &IssueFilter{
|
|
Labels: labels,
|
|
Milestone: milestone,
|
|
Assignee: assignee,
|
|
}
|
|
if projectStr != "" {
|
|
if pid, err := strconv.Atoi(projectStr); err == nil {
|
|
filter.ProjectID = pid
|
|
}
|
|
}
|
|
return filter
|
|
}
|
|
|
|
// SetFilter overrides the tracker's issue filter.
|
|
// CLI flags use this to override config-based defaults.
|
|
func (t *Tracker) SetFilter(filter *IssueFilter) {
|
|
t.filter = filter
|
|
}
|
|
|
|
func (t *Tracker) Validate() error {
|
|
if t.client == nil {
|
|
return fmt.Errorf("GitLab tracker not initialized")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (t *Tracker) Close() error { return nil }
|
|
|
|
func (t *Tracker) FetchIssues(ctx context.Context, opts tracker.FetchOptions) ([]tracker.TrackerIssue, error) {
|
|
var issues []Issue
|
|
var err error
|
|
|
|
state := opts.State
|
|
if state == "" {
|
|
state = "all"
|
|
}
|
|
// GitLab uses "opened" not "open"
|
|
if state == "open" {
|
|
state = "opened"
|
|
}
|
|
|
|
if opts.Since != nil {
|
|
issues, err = t.client.FetchIssuesSince(ctx, state, *opts.Since, t.filter)
|
|
} else {
|
|
issues, err = t.client.FetchIssues(ctx, state, t.filter)
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Enrich each issue with its links (dependencies).
|
|
for i := range issues {
|
|
links, err := t.client.GetIssueLinks(ctx, issues[i].IID)
|
|
if err != nil {
|
|
// Non-fatal: issue may lack link permissions or be in a different project.
|
|
continue
|
|
}
|
|
issues[i].IssueLinksData = links
|
|
}
|
|
|
|
result := make([]tracker.TrackerIssue, 0, len(issues))
|
|
for _, gl := range issues {
|
|
result = append(result, gitlabToTrackerIssue(&gl))
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (t *Tracker) FetchIssue(ctx context.Context, identifier string) (*tracker.TrackerIssue, error) {
|
|
if milestoneIID, ok, err := parseMilestoneIdentifier(identifier); ok || err != nil {
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ms, err := t.client.FetchMilestoneByIID(ctx, milestoneIID)
|
|
if err != nil || ms == nil {
|
|
return nil, err
|
|
}
|
|
ti := milestoneToTrackerIssue(ms)
|
|
return ti, nil
|
|
}
|
|
|
|
iid, err := strconv.Atoi(identifier)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid GitLab IID %q: %w", identifier, err)
|
|
}
|
|
|
|
gl, err := t.client.FetchIssueByIID(ctx, iid)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if gl == nil {
|
|
return nil, nil
|
|
}
|
|
|
|
ti := gitlabToTrackerIssue(gl)
|
|
return &ti, nil
|
|
}
|
|
|
|
func (t *Tracker) CreateIssue(ctx context.Context, issue *types.Issue) (*tracker.TrackerIssue, error) {
|
|
// Epic → milestone
|
|
if issue.IssueType == types.TypeEpic {
|
|
return t.createMilestone(ctx, issue)
|
|
}
|
|
|
|
// Task with a story/feature parent → GitLab Task work item (child of parent Issue)
|
|
if issue.IssueType == types.TypeTask && t.projectPath != "" && t.store != nil {
|
|
if parentGID := t.findParentStoryGID(ctx, issue.ID); parentGID != "" {
|
|
return t.createTaskWorkItem(ctx, issue, parentGID)
|
|
}
|
|
}
|
|
|
|
fields := BeadsIssueToGitLabFields(issue, t.config)
|
|
labels, _ := fields["labels"].([]string)
|
|
|
|
created, err := t.client.CreateIssue(ctx, issue.Title, issue.Description, labels)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Assign milestone from parent epic if one exists
|
|
if t.store != nil {
|
|
if milestoneID := t.findParentEpicMilestone(ctx, issue.ID); milestoneID > 0 {
|
|
_, _ = t.client.UpdateIssue(ctx, created.IID, map[string]interface{}{
|
|
"milestone_id": milestoneID,
|
|
})
|
|
}
|
|
}
|
|
|
|
// GitLab's POST /issues cannot set state, so a closed bead is created
|
|
// "opened". Close it with a follow-up update so the state carries. On
|
|
// failure we keep the created issue and its external_ref (returning an error
|
|
// here would strand the issue and re-create a duplicate on the next push).
|
|
// The trade-off: the push skip-guard treats the just-created remote as
|
|
// up-to-date, so a failed close is not retried until the bead is next
|
|
// modified — hence the warning. A closed-state push is the common bulk case
|
|
// and this call rarely fails.
|
|
var warnings []string
|
|
if issue.Status == types.StatusClosed {
|
|
if closed, err := t.client.UpdateIssue(ctx, created.IID, map[string]interface{}{
|
|
"state_event": "close",
|
|
}); err == nil {
|
|
created = closed
|
|
} else {
|
|
warnings = append(warnings, fmt.Sprintf("created GitLab issue %d but failed to close it (left open): %v", created.IID, err))
|
|
}
|
|
}
|
|
|
|
ti := gitlabToTrackerIssue(created)
|
|
ti.Warnings = warnings
|
|
return &ti, nil
|
|
}
|
|
|
|
func (t *Tracker) UpdateIssue(ctx context.Context, externalID string, issue *types.Issue) (*tracker.TrackerIssue, error) {
|
|
// Epic → milestone
|
|
if issue.IssueType == types.TypeEpic {
|
|
return t.updateMilestone(ctx, externalID, issue)
|
|
}
|
|
|
|
iid, err := strconv.Atoi(externalID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid GitLab IID %q: %w", externalID, err)
|
|
}
|
|
|
|
updates := BeadsIssueToGitLabFields(issue, t.config)
|
|
|
|
// Assign milestone from parent epic if one exists
|
|
if t.store != nil {
|
|
if milestoneID := t.findParentEpicMilestone(ctx, issue.ID); milestoneID > 0 {
|
|
updates["milestone_id"] = milestoneID
|
|
}
|
|
}
|
|
|
|
updated, err := t.client.UpdateIssue(ctx, iid, updates)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
ti := gitlabToTrackerIssue(updated)
|
|
return &ti, nil
|
|
}
|
|
|
|
// createMilestone creates a GitLab milestone for an epic bead.
|
|
func (t *Tracker) createMilestone(ctx context.Context, issue *types.Issue) (*tracker.TrackerIssue, error) {
|
|
ms, err := t.client.CreateMilestone(ctx, issue.Title, issue.Description)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("creating milestone for epic: %w", err)
|
|
}
|
|
|
|
// Milestones are created active; close it with a follow-up update if the
|
|
// epic is closed so its state carries. Best effort with the same failure
|
|
// trade-off as CreateIssue (a failed close is not retried until the epic is
|
|
// next modified).
|
|
var warnings []string
|
|
if issue.Status == types.StatusClosed {
|
|
if closed, err := t.client.UpdateMilestone(ctx, ms.ID, map[string]interface{}{
|
|
"state_event": "close",
|
|
}); err == nil {
|
|
ms = closed
|
|
} else {
|
|
warnings = append(warnings, fmt.Sprintf("created GitLab milestone %d but failed to close it (left active): %v", ms.ID, err))
|
|
}
|
|
}
|
|
ti := milestoneToTrackerIssue(ms)
|
|
ti.Warnings = warnings
|
|
return ti, nil
|
|
}
|
|
|
|
// updateMilestone updates a GitLab milestone for an epic bead.
|
|
func (t *Tracker) updateMilestone(ctx context.Context, externalID string, issue *types.Issue) (*tracker.TrackerIssue, error) {
|
|
mid, ok, err := parseMilestoneIdentifier(externalID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !ok {
|
|
mid, err = strconv.Atoi(externalID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid milestone ID %q: %w", externalID, err)
|
|
}
|
|
}
|
|
apiID := mid
|
|
msByIID, err := t.client.FetchMilestoneByIID(ctx, mid)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("resolving milestone IID %d: %w", mid, err)
|
|
}
|
|
if msByIID != nil {
|
|
apiID = msByIID.ID
|
|
}
|
|
|
|
updates := map[string]interface{}{
|
|
"title": issue.Title,
|
|
"description": issue.Description,
|
|
}
|
|
if issue.Status == types.StatusClosed {
|
|
updates["state_event"] = "close"
|
|
} else {
|
|
updates["state_event"] = "activate"
|
|
}
|
|
|
|
ms, err := t.client.UpdateMilestone(ctx, apiID, updates)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("updating milestone for epic: %w", err)
|
|
}
|
|
return milestoneToTrackerIssue(ms), nil
|
|
}
|
|
|
|
// findParentEpicMilestone walks up the parent-child chain from an issue
|
|
// to find an ancestor epic, then returns its GitLab milestone API ID.
|
|
// Returns 0 if no epic ancestor or no milestone found.
|
|
func (t *Tracker) findParentEpicMilestone(ctx context.Context, issueID string) int {
|
|
// Walk up parent chain (max 5 levels to prevent loops)
|
|
currentID := issueID
|
|
for i := 0; i < 5; i++ {
|
|
deps, err := t.store.GetDependenciesWithMetadata(ctx, currentID)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
foundParent := false
|
|
for _, dep := range deps {
|
|
if dep.DependencyType != types.DepParentChild {
|
|
continue
|
|
}
|
|
if dep.Issue.IssueType == types.TypeEpic {
|
|
// Found the epic — extract milestone IID from its external ref
|
|
ref := ""
|
|
if dep.Issue.ExternalRef != nil {
|
|
ref = *dep.Issue.ExternalRef
|
|
}
|
|
if ref == "" {
|
|
return 0
|
|
}
|
|
matches := milestoneIDPattern.FindStringSubmatch(ref)
|
|
if len(matches) < 2 {
|
|
return 0
|
|
}
|
|
milestoneIID, err := strconv.Atoi(matches[1])
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
// Look up API ID by IID (single API call instead of fetching all milestones)
|
|
ms, err := t.client.FetchMilestoneByIID(ctx, milestoneIID)
|
|
if err != nil || ms == nil {
|
|
return 0
|
|
}
|
|
return ms.ID
|
|
}
|
|
// Not an epic — keep walking up
|
|
currentID = dep.Issue.ID
|
|
foundParent = true
|
|
break
|
|
}
|
|
if !foundParent {
|
|
return 0
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// createTaskWorkItem creates a GitLab Task work item as a child of a parent Issue.
|
|
func (t *Tracker) createTaskWorkItem(ctx context.Context, issue *types.Issue, parentGID string) (*tracker.TrackerIssue, error) {
|
|
wi, err := t.client.CreateTaskWorkItem(ctx, t.projectPath, issue.Title, issue.Description, parentGID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("creating task work item: %w", err)
|
|
}
|
|
|
|
// Build URL from project path and IID
|
|
webURL := fmt.Sprintf("%s/%s/-/work_items/%s", t.client.BaseURL, t.projectPath, wi.IID)
|
|
|
|
iid, _ := strconv.Atoi(wi.IID)
|
|
|
|
// Also set milestone if there's a grandparent epic
|
|
if milestoneID := t.findParentEpicMilestone(ctx, issue.ID); milestoneID > 0 {
|
|
if iid > 0 {
|
|
_, _ = t.client.UpdateIssue(ctx, iid, map[string]interface{}{
|
|
"milestone_id": milestoneID,
|
|
})
|
|
}
|
|
}
|
|
|
|
// Work items are created open; close via the issues API (work items share
|
|
// the project IID space, as the milestone assignment above relies on) if the
|
|
// bead is closed. Best effort with the same failure trade-off as CreateIssue.
|
|
var warnings []string
|
|
if issue.Status == types.StatusClosed && iid > 0 {
|
|
if _, err := t.client.UpdateIssue(ctx, iid, map[string]interface{}{
|
|
"state_event": "close",
|
|
}); err != nil {
|
|
warnings = append(warnings, fmt.Sprintf("created GitLab work item %s but failed to close it (left open): %v", wi.IID, err))
|
|
}
|
|
}
|
|
|
|
return &tracker.TrackerIssue{
|
|
ID: wi.ID,
|
|
Identifier: wi.IID,
|
|
URL: webURL,
|
|
Title: wi.Title,
|
|
Warnings: warnings,
|
|
}, nil
|
|
}
|
|
|
|
// findParentStoryGID finds the GitLab global ID (gid://...) of a parent story/feature.
|
|
// Returns empty string if no story/feature parent or if the parent isn't synced to GitLab.
|
|
func (t *Tracker) findParentStoryGID(ctx context.Context, issueID string) string {
|
|
deps, err := t.store.GetDependenciesWithMetadata(ctx, issueID)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
for _, dep := range deps {
|
|
if dep.DependencyType != types.DepParentChild {
|
|
continue
|
|
}
|
|
// Only match story/feature parents (not epics — those become milestones)
|
|
if dep.Issue.IssueType == types.TypeEpic {
|
|
continue
|
|
}
|
|
ref := ""
|
|
if dep.Issue.ExternalRef != nil {
|
|
ref = *dep.Issue.ExternalRef
|
|
}
|
|
if ref == "" {
|
|
continue
|
|
}
|
|
// Extract IID from the issue URL and look up the GID
|
|
matches := issueIIDPattern.FindStringSubmatch(ref)
|
|
if len(matches) < 2 {
|
|
continue
|
|
}
|
|
iid, err := strconv.Atoi(matches[1])
|
|
if err != nil {
|
|
continue
|
|
}
|
|
gid, err := t.client.GetWorkItemGID(ctx, t.projectPath, iid)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
return gid
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// milestoneToTrackerIssue converts a GitLab Milestone to a TrackerIssue.
|
|
func milestoneToTrackerIssue(ms *Milestone) *tracker.TrackerIssue {
|
|
ti := &tracker.TrackerIssue{
|
|
ID: strconv.Itoa(ms.ID),
|
|
Identifier: strconv.Itoa(ms.ID),
|
|
URL: ms.WebURL,
|
|
Title: ms.Title,
|
|
Description: ms.Description,
|
|
State: ms.State,
|
|
}
|
|
if ms.CreatedAt != nil {
|
|
ti.CreatedAt = *ms.CreatedAt
|
|
}
|
|
if ms.UpdatedAt != nil {
|
|
ti.UpdatedAt = *ms.UpdatedAt
|
|
}
|
|
return ti
|
|
}
|
|
|
|
func (t *Tracker) FieldMapper() tracker.FieldMapper {
|
|
return &gitlabFieldMapper{config: t.config}
|
|
}
|
|
|
|
// IsExternalRef checks if a ref belongs to this GitLab tracker.
|
|
// It recognizes both full GitLab URLs and the "gitlab:{id}" shorthand format
|
|
// produced by BuildExternalRef when a URL is unavailable.
|
|
func (t *Tracker) IsExternalRef(ref string) bool {
|
|
if glShorthandPattern.MatchString(ref) {
|
|
return true
|
|
}
|
|
if !strings.Contains(ref, "gitlab") && !strings.Contains(ref, "milestones") {
|
|
return false
|
|
}
|
|
return issueIIDPattern.MatchString(ref) || milestoneIDPattern.MatchString(ref)
|
|
}
|
|
|
|
// ExtractIdentifier extracts the issue IID from a GitLab URL or shorthand ref.
|
|
func (t *Tracker) ExtractIdentifier(ref string) string {
|
|
if m := glShorthandPattern.FindStringSubmatch(ref); len(m) >= 2 {
|
|
return m[1]
|
|
}
|
|
// Try milestone pattern first (more specific path)
|
|
if matches := milestoneIDPattern.FindStringSubmatch(ref); len(matches) >= 2 {
|
|
return gitLabMilestoneIdentifierPrefix + matches[1]
|
|
}
|
|
// Fall back to issue pattern
|
|
if matches := issueIIDPattern.FindStringSubmatch(ref); len(matches) >= 2 {
|
|
return matches[1]
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func parseMilestoneIdentifier(identifier string) (int, bool, error) {
|
|
if !strings.HasPrefix(identifier, gitLabMilestoneIdentifierPrefix) {
|
|
return 0, false, nil
|
|
}
|
|
raw := strings.TrimPrefix(identifier, gitLabMilestoneIdentifierPrefix)
|
|
iid, err := strconv.Atoi(raw)
|
|
if err != nil {
|
|
return 0, true, fmt.Errorf("invalid GitLab milestone identifier %q: %w", identifier, err)
|
|
}
|
|
return iid, true, nil
|
|
}
|
|
|
|
// IsMilestoneRef checks if an external_ref points to a milestone (not an issue).
|
|
func (t *Tracker) IsMilestoneRef(ref string) bool {
|
|
return milestoneIDPattern.MatchString(ref)
|
|
}
|
|
|
|
func (t *Tracker) BuildExternalRef(issue *tracker.TrackerIssue) string {
|
|
if issue.URL != "" {
|
|
return issue.URL
|
|
}
|
|
return fmt.Sprintf("gitlab:%s", issue.Identifier)
|
|
}
|
|
|
|
// getConfig reads a config value from storage, falling back to env var.
|
|
// For yaml-only keys (e.g. gitlab.token), reads from config.yaml first
|
|
// to avoid leaking secrets when pushing the Dolt database to remotes.
|
|
func (t *Tracker) getConfig(ctx context.Context, key, envVar string) (string, error) {
|
|
// Secret keys are stored in config.yaml, not the Dolt database,
|
|
// to avoid leaking secrets when pushing to remotes.
|
|
if config.IsYamlOnlyKey(key) {
|
|
if val := config.GetString(key); val != "" {
|
|
return val, nil
|
|
}
|
|
if envVar != "" {
|
|
if envVal := os.Getenv(envVar); envVal != "" {
|
|
return envVal, nil
|
|
}
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
val, err := t.store.GetConfig(ctx, key)
|
|
if err == nil && val != "" {
|
|
return val, nil
|
|
}
|
|
if envVar != "" {
|
|
if envVal := os.Getenv(envVar); envVal != "" {
|
|
return envVal, nil
|
|
}
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
// gitlabToTrackerIssue converts a gitlab.Issue to a tracker.TrackerIssue.
|
|
func gitlabToTrackerIssue(gl *Issue) tracker.TrackerIssue {
|
|
ti := tracker.TrackerIssue{
|
|
ID: strconv.Itoa(gl.ID),
|
|
Identifier: strconv.Itoa(gl.IID),
|
|
URL: gl.WebURL,
|
|
Title: gl.Title,
|
|
Description: gl.Description,
|
|
Labels: gl.Labels,
|
|
Raw: gl,
|
|
}
|
|
|
|
if gl.State != "" {
|
|
ti.State = gl.State
|
|
}
|
|
|
|
if gl.Assignee != nil {
|
|
ti.Assignee = gl.Assignee.Username
|
|
ti.AssigneeID = strconv.Itoa(gl.Assignee.ID)
|
|
}
|
|
|
|
if gl.CreatedAt != nil {
|
|
ti.CreatedAt = *gl.CreatedAt
|
|
}
|
|
if gl.UpdatedAt != nil {
|
|
ti.UpdatedAt = *gl.UpdatedAt
|
|
}
|
|
if gl.ClosedAt != nil {
|
|
ti.CompletedAt = gl.ClosedAt
|
|
}
|
|
|
|
return ti
|
|
}
|