* 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>
1496 lines
50 KiB
Go
1496 lines
50 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/debug"
|
|
"github.com/steveyegge/beads/internal/linear"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/tracker"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
// linearCmd is the root command for Linear integration.
|
|
var linearCmd = &cobra.Command{
|
|
Use: "linear",
|
|
GroupID: "advanced",
|
|
Short: "Linear integration commands",
|
|
Long: `Synchronize issues between beads and Linear.
|
|
|
|
Configuration:
|
|
bd config set linear.api_key "YOUR_API_KEY"
|
|
bd config set linear.team_id "TEAM_ID"
|
|
bd config set linear.team_ids "TEAM_ID1,TEAM_ID2" # Multiple teams (comma-separated)
|
|
bd config set linear.project_id "PROJECT_ID" # Optional: sync only this project
|
|
|
|
Environment variables (alternative to config):
|
|
LINEAR_API_KEY - Linear API key (for individual developers)
|
|
LINEAR_TEAM_ID - Linear team ID (UUID, singular)
|
|
LINEAR_TEAM_IDS - Linear team IDs (comma-separated UUIDs)
|
|
|
|
OAuth (for CI workers / automated sync):
|
|
LINEAR_OAUTH_CLIENT_ID - OAuth app client ID
|
|
LINEAR_OAUTH_CLIENT_SECRET - OAuth app client secret
|
|
|
|
When both OAuth env vars are set, OAuth client_credentials flow is used
|
|
instead of the API key. This allows CI workers to authenticate as an
|
|
application (actor=application) rather than impersonating a user.
|
|
Precedence: OAuth > LINEAR_API_KEY > config file.
|
|
|
|
Data Mapping (optional, sensible defaults provided):
|
|
Priority mapping (Linear 0-4 to Beads 0-4):
|
|
bd config set linear.priority_map.0 4 # No priority -> Backlog
|
|
bd config set linear.priority_map.1 0 # Urgent -> Critical
|
|
bd config set linear.priority_map.2 1 # High -> High
|
|
bd config set linear.priority_map.3 2 # Medium -> Medium
|
|
bd config set linear.priority_map.4 3 # Low -> Low
|
|
|
|
State mapping (Linear state type to Beads status):
|
|
bd config set linear.state_map.backlog open
|
|
bd config set linear.state_map.unstarted open
|
|
bd config set linear.state_map.started in_progress
|
|
bd config set linear.state_map.completed closed
|
|
bd config set linear.state_map.canceled closed
|
|
bd config set linear.state_map.my_custom_state in_progress # Custom state names
|
|
|
|
Label to issue type mapping:
|
|
bd config set linear.label_type_map.bug bug
|
|
bd config set linear.label_type_map.feature feature
|
|
bd config set linear.label_type_map.epic epic
|
|
|
|
Relation type mapping (Linear relations to Beads dependencies):
|
|
bd config set linear.relation_map.blocks blocks
|
|
bd config set linear.relation_map.blockedBy blocks
|
|
bd config set linear.relation_map.duplicate duplicates
|
|
bd config set linear.relation_map.related related
|
|
|
|
ID generation (optional, hash IDs to match bd/Jira hash mode):
|
|
bd config set linear.id_mode "hash" # hash (default)
|
|
bd config set linear.hash_length "6" # hash length 3-8 (default: 6)
|
|
|
|
Examples:
|
|
bd linear sync --pull # Import issues from Linear
|
|
bd linear sync --push # Export issues to Linear
|
|
bd linear sync # Bidirectional sync (pull then push)
|
|
bd linear sync --dry-run # Preview sync without changes
|
|
bd create "Fix login" --external-ref https://linear.app/team/issue/TEAM-123
|
|
# Link a local issue to an existing Linear issue
|
|
bd linear status # Show sync status`,
|
|
}
|
|
|
|
// linearSyncCmd handles synchronization with Linear.
|
|
var linearSyncCmd = &cobra.Command{
|
|
Use: "sync",
|
|
Short: "Synchronize issues with Linear",
|
|
Long: `Synchronize issues between beads and Linear.
|
|
|
|
Modes:
|
|
--pull Import issues from Linear into beads
|
|
--push Export issues from beads to Linear
|
|
--pull-if-stale Pull only if data is stale (skip if fresh)
|
|
(no flags) Bidirectional sync: pull then push, with conflict resolution
|
|
|
|
Staleness (--pull-if-stale):
|
|
--threshold 20m How old data must be before pulling (default 20m)
|
|
A 5-minute debounce prevents agent loops: if a pull completed within 5 minutes,
|
|
data is always treated as fresh regardless of the threshold.
|
|
|
|
Team Selection:
|
|
--team ID1,ID2 Override configured team IDs for this sync
|
|
Multiple teams can be configured via linear.team_ids (comma-separated).
|
|
Falls back to linear.team_id for backward compatibility.
|
|
Push requires explicit --team when multiple teams are configured.
|
|
|
|
Pull Options:
|
|
--milestones Reconstruct Linear project milestones as local epic parents
|
|
|
|
Type Filtering (--push only):
|
|
--type task,feature Only sync issues of these types
|
|
--exclude-type wisp Exclude issues of these types
|
|
--include-ephemeral Include ephemeral issues (wisps, etc.); default is to exclude
|
|
--parent TICKET Only push this ticket and its descendants
|
|
--relations Import Linear relations as bd dependencies on pull
|
|
|
|
Persistent push-direction ID filters (workflow artifacts, sandbox beads, etc.):
|
|
bd config set linear.exclude_id_prefix "hw-mol-"
|
|
bd config set linear.exclude_id_patterns "-wisp-,sandbox-,scratch-"
|
|
|
|
exclude_id_prefix is a single case-sensitive prefix on the bead ID.
|
|
exclude_id_patterns is a comma-separated list of case-sensitive substrings
|
|
(matched anywhere in the ID). Both are combined as a union: a bead
|
|
matching either rule is skipped from push (no create, no update). Beads
|
|
with an existing external_ref that NOW match are silently skipped on
|
|
future syncs; the Linear-side issue persists — archive/delete it manually
|
|
if desired.
|
|
|
|
Conflict Resolution:
|
|
By default, newer timestamp wins. Override with:
|
|
--prefer-local Always prefer local beads version
|
|
--prefer-linear Always prefer Linear version
|
|
|
|
Examples:
|
|
bd linear sync --pull # Import from Linear
|
|
bd linear sync --pull-if-stale # Pull only if data is stale
|
|
bd linear sync --pull-if-stale --threshold 5m # Pull if older than 5 minutes
|
|
bd linear sync --pull --relations # Import Linear blocking relations as bd deps
|
|
bd linear sync --push --create-only # Push new issues only
|
|
bd linear sync --push --type=task,feature # Push only tasks and features
|
|
bd linear sync --push --exclude-type=wisp # Push all except wisps
|
|
bd linear sync --push --parent=bd-abc123 # Push one ticket tree
|
|
bd linear sync --dry-run # Preview without changes
|
|
bd linear sync --prefer-local # Bidirectional, local wins`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: runLinearSync,
|
|
}
|
|
|
|
// linearStatusCmd shows the current sync status.
|
|
var linearStatusCmd = &cobra.Command{
|
|
Use: "status",
|
|
Short: "Show Linear sync status",
|
|
Long: `Show the current Linear sync status, including:
|
|
- Last sync timestamp
|
|
- Configuration status
|
|
- Number of issues with Linear links
|
|
- Issues pending push (no external_ref)`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: runLinearStatus,
|
|
}
|
|
|
|
// linearTeamsCmd lists available teams.
|
|
var linearTeamsCmd = &cobra.Command{
|
|
Use: "teams",
|
|
Short: "List available Linear teams",
|
|
Long: `List all teams accessible with your Linear API key.
|
|
|
|
Use this to find the team ID (UUID) needed for configuration.
|
|
|
|
Example:
|
|
bd linear teams
|
|
bd config set linear.team_id "12345678-1234-1234-1234-123456789abc"`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: runLinearTeams,
|
|
}
|
|
|
|
func init() {
|
|
linearSyncCmd.Flags().Bool("pull", false, "Pull issues from Linear")
|
|
linearSyncCmd.Flags().Bool("push", false, "Push issues to Linear")
|
|
linearSyncCmd.Flags().Bool("dry-run", false, "Preview sync without making changes")
|
|
linearSyncCmd.Flags().Bool("prefer-local", false, "Prefer local version on conflicts")
|
|
linearSyncCmd.Flags().Bool("prefer-linear", false, "Prefer Linear version on conflicts")
|
|
linearSyncCmd.Flags().Bool("create-only", false, "Only create new issues, don't update existing")
|
|
linearSyncCmd.Flags().Bool("update-refs", true, "Update external_ref after creating Linear issues")
|
|
linearSyncCmd.Flags().Bool("milestones", false, "Reconstruct Linear project milestones as local epic parents when pulling")
|
|
linearSyncCmd.Flags().String("state", "all", "Issue state to sync: open, closed, all")
|
|
linearSyncCmd.Flags().StringSlice("type", nil, "Only sync issues of these types (can be repeated)")
|
|
linearSyncCmd.Flags().StringSlice("exclude-type", nil, "Exclude issues of these types (can be repeated)")
|
|
linearSyncCmd.Flags().Bool("include-ephemeral", false, "Include ephemeral issues (wisps, etc.) when pushing to Linear")
|
|
linearSyncCmd.Flags().String("parent", "", "Limit push to this beads ticket and its descendants")
|
|
linearSyncCmd.Flags().StringSlice("team", nil, "Team ID(s) to sync (overrides configured team_id/team_ids)")
|
|
linearSyncCmd.Flags().Bool("relations", false, "Import Linear relations as bd dependencies when pulling")
|
|
linearSyncCmd.Flags().Bool("pull-if-stale", false, "Pull only if Linear data is stale (skip if fresh)")
|
|
linearSyncCmd.Flags().Duration("threshold", linear.DefaultStaleThreshold, "Staleness threshold for --pull-if-stale (default 20m)")
|
|
linearSyncCmd.Flags().Bool("no-wait", false, "Fail immediately if another sync is running instead of waiting")
|
|
registerSelectiveSyncFlags(linearSyncCmd)
|
|
|
|
linearCmd.AddCommand(linearSyncCmd)
|
|
linearCmd.AddCommand(linearStatusCmd)
|
|
linearCmd.AddCommand(linearTeamsCmd)
|
|
rootCmd.AddCommand(linearCmd)
|
|
}
|
|
|
|
func runLinearSync(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("linear-sync")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
pull, _ := cmd.Flags().GetBool("pull")
|
|
push, _ := cmd.Flags().GetBool("push")
|
|
dryRun, _ := cmd.Flags().GetBool("dry-run")
|
|
preferLocal, _ := cmd.Flags().GetBool("prefer-local")
|
|
preferLinear, _ := cmd.Flags().GetBool("prefer-linear")
|
|
createOnly, _ := cmd.Flags().GetBool("create-only")
|
|
milestones, _ := cmd.Flags().GetBool("milestones")
|
|
state, _ := cmd.Flags().GetString("state")
|
|
typeFilters, _ := cmd.Flags().GetStringSlice("type")
|
|
excludeTypes, _ := cmd.Flags().GetStringSlice("exclude-type")
|
|
includeEphemeral, _ := cmd.Flags().GetBool("include-ephemeral")
|
|
cliTeams, _ := cmd.Flags().GetStringSlice("team")
|
|
relations, _ := cmd.Flags().GetBool("relations")
|
|
pullIfStale, _ := cmd.Flags().GetBool("pull-if-stale")
|
|
threshold, _ := cmd.Flags().GetDuration("threshold")
|
|
noWait, _ := cmd.Flags().GetBool("no-wait")
|
|
|
|
if pullIfStale {
|
|
beadsDir := resolveBeadsDirForStaleness()
|
|
if beadsDir != "" {
|
|
if linear.IsWithinDebounce(beadsDir) {
|
|
info := linear.GetStalenessInfo(beadsDir, threshold)
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"is_fresh": true,
|
|
"last_pull": info.LastPull.Format(time.RFC3339),
|
|
"age": linear.FormatAge(info.Age),
|
|
"skipped": true,
|
|
})
|
|
}
|
|
fmt.Printf("Linear data is fresh (last pull %s ago, within debounce)\n", linear.FormatAge(info.Age))
|
|
return nil
|
|
}
|
|
|
|
if !linear.IsPullStale(beadsDir, threshold) {
|
|
info := linear.GetStalenessInfo(beadsDir, threshold)
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"is_fresh": true,
|
|
"last_pull": info.LastPull.Format(time.RFC3339),
|
|
"age": linear.FormatAge(info.Age),
|
|
"skipped": true,
|
|
})
|
|
}
|
|
fmt.Printf("Linear data is fresh (last pull %s ago)\n", linear.FormatAge(info.Age))
|
|
return nil
|
|
}
|
|
}
|
|
pull = true
|
|
}
|
|
|
|
if lockDir := beads.FindBeadsDir(); lockDir != "" {
|
|
wait := !noWait
|
|
if !wait {
|
|
fmt.Fprintln(os.Stderr, "Acquiring sync lock (non-blocking)...")
|
|
} else {
|
|
fmt.Fprintln(os.Stderr, "Acquiring sync lock...")
|
|
}
|
|
syncLock, err := linear.AcquireSyncLock(lockDir, wait)
|
|
if err != nil {
|
|
if held, ok := err.(*linear.SyncLockHeldError); ok {
|
|
if held.Info != nil {
|
|
return HandleError("another bd linear sync is already running (PID %d, started %s)",
|
|
held.Info.PID, held.Info.Started.Format("15:04:05"))
|
|
}
|
|
return HandleError("another bd linear sync is already running")
|
|
}
|
|
return HandleError("acquiring sync lock: %v", err)
|
|
}
|
|
defer func() {
|
|
if err := syncLock.Release(); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to release sync lock: %v\n", err)
|
|
}
|
|
}()
|
|
}
|
|
|
|
if !dryRun {
|
|
CheckReadonly("linear sync")
|
|
}
|
|
|
|
if preferLocal && preferLinear {
|
|
return HandleErrorRespectJSON("cannot use both --prefer-local and --prefer-linear")
|
|
}
|
|
if milestones && push && !pull {
|
|
return HandleErrorRespectJSON("--milestones only applies when pulling from Linear")
|
|
}
|
|
|
|
trackerStore, err := trackerStoreForCommand(rootCtx)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("database not available: %v", err)
|
|
}
|
|
|
|
if err := validateLinearConfigForStore(trackerStore, cliTeams); err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
|
|
ctx := rootCtx
|
|
teamIDs := getLinearTeamIDsForStore(ctx, trackerStore, cliTeams)
|
|
willPush := push || !pull
|
|
|
|
if willPush && len(teamIDs) > 1 && len(cliTeams) == 0 {
|
|
return HandleErrorRespectJSON("push requires explicit --team flag when multiple teams are configured\n" +
|
|
"Use: bd linear sync --push --team <TEAM_ID>")
|
|
}
|
|
|
|
lt := &linear.Tracker{}
|
|
lt.SetTeamIDs(teamIDs)
|
|
if err := lt.Init(ctx, trackerStore); err != nil {
|
|
return HandleErrorRespectJSON("initializing Linear tracker: %v", err)
|
|
}
|
|
if willPush {
|
|
if err := lt.ValidatePushStateMappings(ctx); err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
}
|
|
|
|
engine := tracker.NewEngine(lt, trackerStore, actor)
|
|
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
|
|
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
|
|
|
|
engine.PullHooks = buildLinearPullHooksForStore(ctx, trackerStore, linearPullHookOptions{
|
|
Milestones: milestones,
|
|
DryRun: dryRun,
|
|
Actor: actor,
|
|
})
|
|
|
|
opts := tracker.SyncOptions{
|
|
Pull: pull,
|
|
Push: push,
|
|
DryRun: dryRun,
|
|
CreateOnly: createOnly,
|
|
State: state,
|
|
}
|
|
opts.DependencySources = linearPullDependencySources(relations)
|
|
|
|
for _, t := range typeFilters {
|
|
opts.TypeFilter = append(opts.TypeFilter, types.IssueType(strings.ToLower(t)))
|
|
}
|
|
for _, t := range excludeTypes {
|
|
opts.ExcludeTypes = append(opts.ExcludeTypes, types.IssueType(strings.ToLower(t)))
|
|
}
|
|
applyLinearExcludeIDConfig(ctx, trackerStore, &opts)
|
|
if !includeEphemeral {
|
|
opts.ExcludeEphemeral = true
|
|
}
|
|
|
|
if err := applySelectiveSyncFlags(cmd, &opts, push); err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
allowProjectCreates := opts.ParentID != "" || len(opts.IssueIDs) > 0
|
|
|
|
engine.PushHooks = buildLinearPushHooksForStore(ctx, trackerStore, lt, allowProjectCreates)
|
|
|
|
if preferLocal {
|
|
opts.ConflictResolution = tracker.ConflictLocal
|
|
} else if preferLinear {
|
|
opts.ConflictResolution = tracker.ConflictExternal
|
|
} else {
|
|
opts.ConflictResolution = tracker.ConflictTimestamp
|
|
}
|
|
|
|
result, err := engine.Sync(ctx, opts)
|
|
if err != nil {
|
|
if jsonOutput {
|
|
if jerr := outputJSON(result); jerr != nil {
|
|
return jerr
|
|
}
|
|
return SilentExit()
|
|
}
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
// Post-sync: reconcile parent-child relationships into Linear's parent
|
|
// field. The per-issue create/update path can't always set parentId
|
|
// (children are sometimes pushed before parents have an external_ref),
|
|
// and previously-pushed orphan trees need a backfill. This pass is
|
|
// idempotent — no API mutation when remote parent already matches.
|
|
//
|
|
// In dry-run mode the pass still runs (read-only fetches) so the user
|
|
// gets a preview of which parents would be set; the IssueUpdate
|
|
// mutation is skipped per-link.
|
|
//
|
|
// Skipped on scoped syncs (--parent / --type / --exclude-type / --since
|
|
// / --issue-id) because the reconciler walks ALL local beads with
|
|
// external_refs, not just the in-scope ones — a scoped sync that
|
|
// silently mutated other parts of the tree would surprise the user.
|
|
// A full sync still picks up the repair on the next run.
|
|
//
|
|
// `effectivePush` mirrors engine.Sync's bidirectional default: when
|
|
// neither --pull nor --push is passed, the engine internally runs both
|
|
// directions, so the reconcile pass must also fire (otherwise
|
|
// `bd linear sync --dry-run` with no direction flag silently skips the
|
|
// preview). We can't read opts.Push after engine.Sync because Sync
|
|
// receives opts by value.
|
|
effectivePush := push || (!push && !pull)
|
|
if effectivePush && result.Success && !syncIsScoped(&opts) {
|
|
reconcileLinearParentsForStore(ctx, trackerStore, lt, dryRun, jsonOutput, &result.Warnings)
|
|
}
|
|
|
|
// Record successful pull timestamp
|
|
if (pull || !push) && !dryRun {
|
|
if beadsDir := resolveBeadsDirForStaleness(); beadsDir != "" {
|
|
_ = linear.WriteLastPullTimestamp(beadsDir)
|
|
}
|
|
}
|
|
|
|
if jsonOutput {
|
|
if pullIfStale {
|
|
return outputJSON(map[string]interface{}{
|
|
"stats": result.Stats,
|
|
"warnings": result.Warnings,
|
|
"is_fresh": true,
|
|
"skipped": false,
|
|
})
|
|
}
|
|
return outputJSON(result)
|
|
}
|
|
if dryRun {
|
|
fmt.Println("\n✓ Dry run complete (no changes made)")
|
|
return nil
|
|
}
|
|
if result.Stats.Pulled > 0 {
|
|
fmt.Printf("✓ Pulled %d issues (%d created, %d updated)\n",
|
|
result.Stats.Pulled, result.Stats.Created, result.Stats.Updated)
|
|
}
|
|
if result.Stats.Pushed > 0 {
|
|
fmt.Printf("✓ Pushed %d issues\n", result.Stats.Pushed)
|
|
}
|
|
if result.Stats.Conflicts > 0 {
|
|
fmt.Printf("→ Resolved %d conflicts\n", result.Stats.Conflicts)
|
|
}
|
|
fmt.Println("\n✓ Linear sync complete")
|
|
if len(result.Warnings) > 0 {
|
|
fmt.Println("\nWarnings:")
|
|
for _, w := range result.Warnings {
|
|
fmt.Printf(" - %s\n", w)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func linearPullDependencySources(includeRelations bool) []tracker.DependencySource {
|
|
if includeRelations {
|
|
return nil
|
|
}
|
|
return []tracker.DependencySource{tracker.DependencySourceParent}
|
|
}
|
|
|
|
type linearPullHookOptions struct {
|
|
Milestones bool
|
|
DryRun bool
|
|
Actor string
|
|
}
|
|
|
|
// buildLinearPullHooks creates PullHooks for Linear-specific pull behavior.
|
|
func buildLinearPullHooks(ctx context.Context, opts linearPullHookOptions) *tracker.PullHooks {
|
|
return buildLinearPullHooksForStore(ctx, tracker.NewStore(store), opts)
|
|
}
|
|
|
|
func buildLinearPullHooksForStore(ctx context.Context, st tracker.Store, opts linearPullHookOptions) *tracker.PullHooks {
|
|
idMode := getLinearIDModeForStore(ctx, st)
|
|
hashLength := getLinearHashLengthForStore(ctx, st)
|
|
|
|
hooks := &tracker.PullHooks{}
|
|
hookActor := opts.Actor
|
|
if hookActor == "" {
|
|
hookActor = actor
|
|
}
|
|
|
|
var generateID func(context.Context, *types.Issue) error
|
|
if idMode == "hash" && st != nil {
|
|
// Pre-load existing IDs for collision avoidance
|
|
existingIssues, err := st.SearchIssues(ctx, "", types.IssueFilter{})
|
|
usedIDs := make(map[string]bool)
|
|
if err == nil {
|
|
for _, issue := range existingIssues {
|
|
if issue.ID != "" {
|
|
usedIDs[issue.ID] = true
|
|
}
|
|
}
|
|
}
|
|
|
|
// YAML config takes precedence — in shared-server mode the DB
|
|
// may belong to a different project (GH#2469).
|
|
prefix := config.GetString("issue-prefix")
|
|
if prefix == "" {
|
|
var err error
|
|
prefix, err = st.GetConfig(ctx, "issue_prefix")
|
|
if err != nil || prefix == "" {
|
|
prefix = "bd"
|
|
}
|
|
}
|
|
|
|
generateID = func(_ context.Context, issue *types.Issue) error {
|
|
ids := []*types.Issue{issue}
|
|
idOpts := linear.IDGenerationOptions{
|
|
BaseLength: hashLength,
|
|
MaxLength: 8,
|
|
UsedIDs: usedIDs,
|
|
}
|
|
if err := linear.GenerateIssueIDs(ids, prefix, "linear-import", idOpts); err != nil {
|
|
return err
|
|
}
|
|
// Track the newly generated ID for future collision avoidance
|
|
usedIDs[issue.ID] = true
|
|
return nil
|
|
}
|
|
hooks.GenerateID = generateID
|
|
}
|
|
|
|
if opts.Milestones && st != nil {
|
|
hooks.AfterConvert = func(ctx context.Context, extIssue *tracker.TrackerIssue, conv *tracker.IssueConversion, ref string, _ *types.Issue, syncOpts tracker.SyncOptions) error {
|
|
li, ok := extIssue.Raw.(*linear.Issue)
|
|
if !ok || li == nil || li.ProjectMilestone == nil {
|
|
return nil
|
|
}
|
|
if syncOpts.DryRun || opts.DryRun {
|
|
return nil
|
|
}
|
|
milestoneRef, err := ensureLinearMilestoneEpic(ctx, st, li.ProjectMilestone, hookActor, generateID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if strings.TrimSpace(ref) == "" {
|
|
return fmt.Errorf("missing external ref for Linear issue %s", extIssue.Identifier)
|
|
}
|
|
conv.Dependencies = append(conv.Dependencies, tracker.DependencyInfo{
|
|
FromExternalID: ref,
|
|
ToExternalID: milestoneRef,
|
|
Type: string(types.DepParentChild),
|
|
Source: tracker.DependencySourceParent,
|
|
})
|
|
return nil
|
|
}
|
|
}
|
|
|
|
return hooks
|
|
}
|
|
|
|
const linearMilestoneExternalRefPrefix = "linear:project-milestone:"
|
|
|
|
func linearMilestoneExternalRef(id string) string {
|
|
return linearMilestoneExternalRefPrefix + strings.TrimSpace(id)
|
|
}
|
|
|
|
func isLinearMilestoneExternalRef(ref string) bool {
|
|
return strings.HasPrefix(strings.TrimSpace(ref), linearMilestoneExternalRefPrefix)
|
|
}
|
|
|
|
func ensureLinearMilestoneEpic(ctx context.Context, st tracker.Store, ms *linear.ProjectMilestone, actor string, generateID func(context.Context, *types.Issue) error) (string, error) {
|
|
milestoneID := strings.TrimSpace(ms.ID)
|
|
if milestoneID == "" {
|
|
return "", fmt.Errorf("Linear project milestone is missing id")
|
|
}
|
|
title := strings.TrimSpace(ms.Name)
|
|
if title == "" {
|
|
title = milestoneID
|
|
}
|
|
description := ms.Description
|
|
ref := linearMilestoneExternalRef(milestoneID)
|
|
|
|
metadata, err := mergedLinearMilestoneMetadata(nil, ms)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
existing, err := findLinearMilestoneEpic(ctx, st, ref, milestoneID, title)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if existing != nil {
|
|
updates := map[string]interface{}{}
|
|
if existing.Title != title {
|
|
updates["title"] = title
|
|
}
|
|
if existing.Description != description {
|
|
updates["description"] = description
|
|
}
|
|
if existing.IssueType != types.TypeEpic {
|
|
updates["issue_type"] = string(types.TypeEpic)
|
|
}
|
|
if existing.ExternalRef == nil || strings.TrimSpace(*existing.ExternalRef) != ref {
|
|
updates["external_ref"] = ref
|
|
}
|
|
mergedMetadata, err := mergedLinearMilestoneMetadata(existing.Metadata, ms)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if string(existing.Metadata) != string(mergedMetadata) {
|
|
updates["metadata"] = mergedMetadata
|
|
}
|
|
if len(updates) > 0 {
|
|
if err := st.UpdateIssue(ctx, existing.ID, updates, actor); err != nil {
|
|
return "", fmt.Errorf("updating Linear milestone epic %s: %w", existing.ID, err)
|
|
}
|
|
}
|
|
return ref, nil
|
|
}
|
|
|
|
externalRef := ref
|
|
epic := &types.Issue{
|
|
Title: title,
|
|
Description: description,
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeEpic,
|
|
ExternalRef: &externalRef,
|
|
Metadata: metadata,
|
|
}
|
|
if generateID != nil {
|
|
if err := generateID(ctx, epic); err != nil {
|
|
return "", fmt.Errorf("generating Linear milestone epic ID: %w", err)
|
|
}
|
|
}
|
|
if err := st.CreateIssue(ctx, epic, actor); err != nil {
|
|
return "", fmt.Errorf("creating Linear milestone epic %q: %w", title, err)
|
|
}
|
|
return ref, nil
|
|
}
|
|
|
|
func findLinearMilestoneEpic(ctx context.Context, st tracker.Store, ref, milestoneID, title string) (*types.Issue, error) {
|
|
if existing, err := st.GetIssueByExternalRef(ctx, ref); err == nil {
|
|
return existing, nil
|
|
} else if !errors.Is(err, storage.ErrNotFound) {
|
|
return nil, err
|
|
}
|
|
|
|
issues, err := st.SearchIssues(ctx, "", types.IssueFilter{})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("searching local issues for Linear milestone %s: %w", milestoneID, err)
|
|
}
|
|
for _, issue := range issues {
|
|
if issueHasLinearMilestoneID(issue, milestoneID) {
|
|
return issue, nil
|
|
}
|
|
}
|
|
|
|
for _, issue := range issues {
|
|
if issue.IssueType != types.TypeEpic || !strings.EqualFold(strings.TrimSpace(issue.Title), title) {
|
|
continue
|
|
}
|
|
ref := ""
|
|
if issue.ExternalRef != nil {
|
|
ref = strings.TrimSpace(*issue.ExternalRef)
|
|
}
|
|
if ref == "" {
|
|
return issue, nil
|
|
}
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
func mergedLinearMilestoneMetadata(existing json.RawMessage, ms *linear.ProjectMilestone) (json.RawMessage, error) {
|
|
data := make(map[string]interface{})
|
|
if len(existing) > 0 {
|
|
trimmed := strings.TrimSpace(string(existing))
|
|
if trimmed != "" && trimmed != "null" {
|
|
if err := json.Unmarshal(existing, &data); err != nil {
|
|
return nil, fmt.Errorf("existing milestone metadata is not a JSON object: %w", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
linearMeta, _ := data["linear"].(map[string]interface{})
|
|
if linearMeta == nil {
|
|
linearMeta = make(map[string]interface{})
|
|
}
|
|
linearMeta["kind"] = "project_milestone"
|
|
linearMeta["project_milestone"] = map[string]interface{}{
|
|
"id": strings.TrimSpace(ms.ID),
|
|
"name": ms.Name,
|
|
"description": ms.Description,
|
|
"progress": ms.Progress,
|
|
"targetDate": ms.TargetDate,
|
|
}
|
|
data["linear"] = linearMeta
|
|
|
|
raw, err := json.Marshal(data)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("marshaling Linear milestone metadata: %w", err)
|
|
}
|
|
return json.RawMessage(raw), nil
|
|
}
|
|
|
|
func issueHasLinearMilestoneID(issue *types.Issue, milestoneID string) bool {
|
|
if issue == nil || len(issue.Metadata) == 0 {
|
|
return false
|
|
}
|
|
var data struct {
|
|
Linear struct {
|
|
Kind string `json:"kind"`
|
|
ProjectMilestone struct {
|
|
ID string `json:"id"`
|
|
} `json:"project_milestone"`
|
|
} `json:"linear"`
|
|
}
|
|
if err := json.Unmarshal(issue.Metadata, &data); err != nil {
|
|
return false
|
|
}
|
|
return data.Linear.Kind == "project_milestone" &&
|
|
strings.TrimSpace(data.Linear.ProjectMilestone.ID) == strings.TrimSpace(milestoneID)
|
|
}
|
|
|
|
func isLinearMilestoneIssue(issue *types.Issue) bool {
|
|
if issue == nil {
|
|
return false
|
|
}
|
|
if issue.ExternalRef != nil && isLinearMilestoneExternalRef(*issue.ExternalRef) {
|
|
return true
|
|
}
|
|
var data struct {
|
|
Linear struct {
|
|
Kind string `json:"kind"`
|
|
} `json:"linear"`
|
|
}
|
|
if len(issue.Metadata) == 0 || json.Unmarshal(issue.Metadata, &data) != nil {
|
|
return false
|
|
}
|
|
return data.Linear.Kind == "project_milestone"
|
|
}
|
|
|
|
// buildLinearPushHooks creates PushHooks for Linear-specific push behavior.
|
|
func buildLinearPushHooks(ctx context.Context, lt *linear.Tracker, allowProjectCreates bool) *tracker.PushHooks {
|
|
return buildLinearPushHooksForStore(ctx, tracker.NewStore(store), lt, allowProjectCreates)
|
|
}
|
|
|
|
func buildLinearPushHooksForStore(ctx context.Context, st tracker.Store, lt *linear.Tracker, allowProjectCreates bool) *tracker.PushHooks {
|
|
config := lt.MappingConfig()
|
|
var labelOnce sync.Once
|
|
var labelCache *linear.LabelCache
|
|
var labelCacheErr error
|
|
loadPushLabelCache := func() *linear.LabelCache {
|
|
labelOnce.Do(func() {
|
|
labelCache, labelCacheErr = linear.BuildLabelCacheFromTracker(ctx, lt)
|
|
})
|
|
if labelCacheErr != nil {
|
|
return nil
|
|
}
|
|
return labelCache
|
|
}
|
|
return &tracker.PushHooks{
|
|
FormatDescription: func(issue *types.Issue) string {
|
|
return linear.BuildLinearDescription(issue)
|
|
},
|
|
ContentEqual: func(local *types.Issue, remote *tracker.TrackerIssue) bool {
|
|
remoteIssue, ok := remote.Raw.(*linear.Issue)
|
|
if ok && remoteIssue != nil {
|
|
return linear.PushFieldsEqual(local, remoteIssue, config, loadPushLabelCache())
|
|
}
|
|
remoteConv := lt.FieldMapper().IssueToBeads(remote)
|
|
if remoteConv == nil || remoteConv.Issue == nil {
|
|
return false
|
|
}
|
|
return linear.PushFieldsEqualToBeads(local, remoteConv.Issue)
|
|
},
|
|
BuildStateCache: func(ctx context.Context) (interface{}, error) {
|
|
return linear.BuildStateCacheFromTracker(ctx, lt)
|
|
},
|
|
ResolveState: func(cache interface{}, status types.Status) (string, bool) {
|
|
sc, ok := cache.(*linear.StateCache)
|
|
if !ok || sc == nil {
|
|
return "", false
|
|
}
|
|
id := sc.FindStateForBeadsStatus(status)
|
|
return id, id != ""
|
|
},
|
|
ShouldPush: func(issue *types.Issue) bool {
|
|
if isLinearMilestoneIssue(issue) {
|
|
return false
|
|
}
|
|
if projectID, _ := st.GetConfig(ctx, "linear.project_id"); projectID != "" {
|
|
if issue.ExternalRef == nil || strings.TrimSpace(*issue.ExternalRef) == "" {
|
|
if !allowProjectCreates {
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
|
|
// Apply push prefix filtering if configured
|
|
pushPrefix, _ := st.GetConfig(ctx, "linear.push_prefix")
|
|
if pushPrefix == "" {
|
|
return true
|
|
}
|
|
for _, prefix := range strings.Split(pushPrefix, ",") {
|
|
prefix = strings.TrimSpace(prefix)
|
|
prefix = strings.TrimSuffix(prefix, "-")
|
|
if prefix != "" && strings.HasPrefix(issue.ID, prefix+"-") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
},
|
|
}
|
|
}
|
|
|
|
func runLinearStatus(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("linear-status")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
ctx := rootCtx
|
|
|
|
trackerStore, err := trackerStoreForCommand(rootCtx)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
|
|
apiKey, _ := getLinearConfigForStore(ctx, trackerStore, "linear.api_key")
|
|
oauthClientID, _ := getLinearConfigForStore(ctx, trackerStore, "linear.oauth_client_id")
|
|
oauthClientSecret, _ := getLinearConfigForStore(ctx, trackerStore, "linear.oauth_client_secret")
|
|
teamIDs := getLinearTeamIDsForStore(ctx, trackerStore, nil)
|
|
lastSync, _ := trackerStore.GetConfig(ctx, "linear.last_sync")
|
|
|
|
hasOAuth := oauthClientID != "" && oauthClientSecret != ""
|
|
configured := (apiKey != "" || hasOAuth) && len(teamIDs) > 0
|
|
|
|
allIssues, err := trackerStore.SearchIssues(ctx, "", types.IssueFilter{})
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("%v", err)
|
|
}
|
|
|
|
withLinearRef := 0
|
|
pendingPush := 0
|
|
for _, issue := range allIssues {
|
|
if issue.ExternalRef != nil && linear.IsLinearExternalRef(*issue.ExternalRef) {
|
|
withLinearRef++
|
|
} else if issue.ExternalRef == nil {
|
|
pendingPush++
|
|
}
|
|
}
|
|
|
|
if jsonOutput {
|
|
hasAPIKey := apiKey != ""
|
|
teamID := ""
|
|
if len(teamIDs) > 0 {
|
|
teamID = teamIDs[0]
|
|
}
|
|
authMode := "none"
|
|
if hasOAuth {
|
|
authMode = "oauth"
|
|
} else if hasAPIKey {
|
|
authMode = "api_key"
|
|
}
|
|
return outputJSON(map[string]interface{}{
|
|
"configured": configured,
|
|
"has_api_key": hasAPIKey,
|
|
"has_oauth": hasOAuth,
|
|
"auth_mode": authMode,
|
|
"team_id": teamID,
|
|
"team_ids": teamIDs,
|
|
"last_sync": lastSync,
|
|
"total_issues": len(allIssues),
|
|
"with_linear_ref": withLinearRef,
|
|
"pending_push": pendingPush,
|
|
})
|
|
}
|
|
|
|
fmt.Println("Linear Sync Status")
|
|
fmt.Println("==================")
|
|
fmt.Println()
|
|
|
|
if !configured {
|
|
fmt.Println("Status: Not configured")
|
|
fmt.Println()
|
|
fmt.Println("To configure Linear integration:")
|
|
fmt.Println(" bd config set linear.api_key \"YOUR_API_KEY\"")
|
|
fmt.Println(" bd config set linear.team_id \"TEAM_ID\"")
|
|
fmt.Println(" bd config set linear.team_ids \"TEAM_ID1,TEAM_ID2\" # multiple teams")
|
|
fmt.Println()
|
|
fmt.Println("Or use environment variables:")
|
|
fmt.Println(" export LINEAR_API_KEY=\"YOUR_API_KEY\"")
|
|
fmt.Println(" export LINEAR_TEAM_ID=\"TEAM_ID\"")
|
|
fmt.Println()
|
|
fmt.Println("For CI/OAuth authentication:")
|
|
fmt.Println(" export LINEAR_OAUTH_CLIENT_ID=\"...\"")
|
|
fmt.Println(" export LINEAR_OAUTH_CLIENT_SECRET=\"...\"")
|
|
return nil
|
|
}
|
|
|
|
if len(teamIDs) == 1 {
|
|
fmt.Printf("Team ID: %s\n", teamIDs[0])
|
|
} else {
|
|
fmt.Printf("Team IDs: %s (%d teams)\n", strings.Join(teamIDs, ", "), len(teamIDs))
|
|
}
|
|
if hasOAuth {
|
|
fmt.Printf("Auth: OAuth (client_credentials)\n")
|
|
} else {
|
|
fmt.Printf("API Key: %s\n", maskAPIKey(apiKey))
|
|
}
|
|
if lastSync != "" {
|
|
fmt.Printf("Last Sync: %s\n", lastSync)
|
|
} else {
|
|
fmt.Println("Last Sync: Never")
|
|
}
|
|
fmt.Println()
|
|
fmt.Printf("Total Issues: %d\n", len(allIssues))
|
|
fmt.Printf("With Linear: %d\n", withLinearRef)
|
|
fmt.Printf("Local Only: %d\n", pendingPush)
|
|
|
|
if pendingPush > 0 {
|
|
fmt.Println()
|
|
fmt.Printf("Run 'bd linear sync --push' to push %d local issue(s) to Linear\n", pendingPush)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func runLinearTeams(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("linear-teams")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
ctx := rootCtx
|
|
|
|
// Team discovery is API-only and must not initialize or probe a local
|
|
// beads store. In proxied mode, read config through the existing UOW seam.
|
|
var configStore tracker.Store
|
|
var err error
|
|
if usesProxiedServer() {
|
|
configStore, err = trackerStoreForCommand(ctx)
|
|
if err != nil {
|
|
return HandleError("database not available: %v", err)
|
|
}
|
|
} else if store != nil {
|
|
configStore = tracker.NewStore(store)
|
|
}
|
|
client, err := buildLinearClientAPIOnly(ctx, "", configStore)
|
|
if err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
teams, err := client.FetchTeams(ctx)
|
|
if err != nil {
|
|
return HandleError("fetching teams: %v", err)
|
|
}
|
|
|
|
if len(teams) == 0 {
|
|
fmt.Println("No teams found (check your API key permissions)")
|
|
return nil
|
|
}
|
|
|
|
if jsonOutput {
|
|
return outputJSON(teams)
|
|
}
|
|
|
|
fmt.Println("Available Linear Teams")
|
|
fmt.Println("======================")
|
|
fmt.Println()
|
|
fmt.Printf("%-40s %-6s %s\n", "ID (use this for linear.team_id)", "Key", "Name")
|
|
fmt.Printf("%-40s %-6s %s\n", "----------------------------------------", "------", "----")
|
|
for _, team := range teams {
|
|
fmt.Printf("%-40s %-6s %s\n", team.ID, team.Key, team.Name)
|
|
}
|
|
fmt.Println()
|
|
fmt.Println("To configure:")
|
|
fmt.Println(" bd config set linear.team_id \"<ID>\"")
|
|
fmt.Println(" bd config set linear.team_ids \"<ID1>,<ID2>\" # multiple teams")
|
|
return nil
|
|
}
|
|
|
|
// resolveBeadsDirForStaleness returns the active beads directory for
|
|
// staleness tracking. Falls back to BEADS_DIR env, then dbPath resolution.
|
|
func resolveBeadsDirForStaleness() string {
|
|
if dir := os.Getenv("BEADS_DIR"); dir != "" {
|
|
return dir
|
|
}
|
|
if dbPath != "" {
|
|
return resolveCommandBeadsDir(dbPath)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// uuidRegex matches valid UUID format (with or without hyphens).
|
|
var uuidRegex = regexp.MustCompile(`^[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}$`)
|
|
|
|
func isValidUUID(s string) bool {
|
|
return uuidRegex.MatchString(s)
|
|
}
|
|
|
|
// validateLinearConfig checks that required Linear configuration is present.
|
|
// cliTeams is the list of team IDs from the --team flag (may be nil).
|
|
func validateLinearConfig(cliTeams []string) error {
|
|
return validateLinearConfigForStore(tracker.NewStore(store), cliTeams)
|
|
}
|
|
|
|
func validateLinearConfigForStore(st tracker.Store, cliTeams []string) error {
|
|
ctx := rootCtx
|
|
|
|
// Accept either OAuth credentials or API key.
|
|
oauthClientID, _ := getLinearConfigForStore(ctx, st, "linear.oauth_client_id")
|
|
oauthClientSecret, _ := getLinearConfigForStore(ctx, st, "linear.oauth_client_secret")
|
|
hasOAuth := oauthClientID != "" && oauthClientSecret != ""
|
|
|
|
if !hasOAuth {
|
|
apiKey, _ := getLinearConfigForStore(ctx, st, "linear.api_key")
|
|
if apiKey == "" {
|
|
return fmt.Errorf("Linear authentication not configured\n" +
|
|
"Options:\n" +
|
|
" OAuth (for CI): export LINEAR_OAUTH_CLIENT_ID=... LINEAR_OAUTH_CLIENT_SECRET=...\n" +
|
|
" API key (devs): export LINEAR_API_KEY=... or bd config set linear.api_key \"YOUR_API_KEY\"")
|
|
}
|
|
}
|
|
|
|
teamIDs := getLinearTeamIDsForStore(ctx, st, cliTeams)
|
|
if len(teamIDs) == 0 {
|
|
return fmt.Errorf("no Linear team ID configured\nRun: bd config set linear.team_id \"TEAM_ID\"\nOr: bd config set linear.team_ids \"TEAM_ID1,TEAM_ID2\"\nOr: export LINEAR_TEAM_ID=TEAM_ID")
|
|
}
|
|
|
|
for _, id := range teamIDs {
|
|
if !isValidUUID(id) {
|
|
return fmt.Errorf("invalid Linear team ID (expected UUID format like '12345678-1234-1234-1234-123456789abc')\nInvalid value: %s", id)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// maskAPIKey returns a masked version of an API key for display.
|
|
// Shows first 4 and last 4 characters, with dots in between.
|
|
func maskAPIKey(key string) string {
|
|
if len(key) <= 8 {
|
|
return "****"
|
|
}
|
|
return key[:4] + "..." + key[len(key)-4:]
|
|
}
|
|
|
|
// getLinearConfig reads a Linear configuration value. Returns the value and its source.
|
|
// Priority: environment variable > project config.
|
|
// Env vars take precedence so CI workers can override config without modifying config.yaml.
|
|
func getLinearConfig(ctx context.Context, key string) (value string, source string) {
|
|
return getLinearConfigForStore(ctx, tracker.NewStore(store), key)
|
|
}
|
|
|
|
func getLinearConfigForStore(ctx context.Context, st tracker.Store, key string) (value string, source string) {
|
|
// Secret keys (e.g. linear.api_key) are stored in config.yaml, not the
|
|
// Dolt database, to avoid leaking secrets when pushing to remotes.
|
|
// Env vars are checked first so that LINEAR_OAUTH_CLIENT_ID/SECRET etc.
|
|
// override whatever is in config.yaml.
|
|
if config.IsYamlOnlyKey(key) {
|
|
envKey := linearConfigToEnvVar(key)
|
|
if envKey != "" {
|
|
if value := os.Getenv(envKey); value != "" {
|
|
return value, fmt.Sprintf("environment variable (%s)", envKey)
|
|
}
|
|
}
|
|
if value := config.GetString(key); value != "" {
|
|
return value, "project config (config.yaml)"
|
|
}
|
|
return "", ""
|
|
}
|
|
|
|
// Try to read from store (works in direct mode)
|
|
if st != nil {
|
|
value, _ = st.GetConfig(ctx, key) // Best effort: empty value is valid fallback
|
|
if value != "" {
|
|
return value, "project config (bd config)"
|
|
}
|
|
} else if dbPath != "" {
|
|
tempStore, err := openReadOnlyStoreForDBPath(ctx, dbPath)
|
|
if err == nil {
|
|
defer func() { _ = tempStore.Close() }()
|
|
value, _ = tempStore.GetConfig(ctx, key) // Best effort: empty value is valid fallback
|
|
if value != "" {
|
|
return value, "project config (bd config)"
|
|
}
|
|
}
|
|
}
|
|
|
|
// Fall back to environment variable
|
|
envKey := linearConfigToEnvVar(key)
|
|
if envKey != "" {
|
|
value = os.Getenv(envKey)
|
|
if value != "" {
|
|
return value, fmt.Sprintf("environment variable (%s)", envKey)
|
|
}
|
|
}
|
|
|
|
return "", ""
|
|
}
|
|
|
|
// linearConfigToEnvVar maps Linear config keys to their environment variable names.
|
|
func linearConfigToEnvVar(key string) string {
|
|
switch key {
|
|
case "linear.api_key":
|
|
return "LINEAR_API_KEY"
|
|
case "linear.team_id":
|
|
return "LINEAR_TEAM_ID"
|
|
case "linear.team_ids":
|
|
return "LINEAR_TEAM_IDS"
|
|
case "linear.oauth_client_id":
|
|
return "LINEAR_OAUTH_CLIENT_ID"
|
|
case "linear.oauth_client_secret":
|
|
return "LINEAR_OAUTH_CLIENT_SECRET"
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
// getLinearTeamIDs resolves the effective team IDs from all config sources.
|
|
// Precedence: cliTeams (--team flag) > linear.team_ids > LINEAR_TEAM_IDS > linear.team_id > LINEAR_TEAM_ID
|
|
func getLinearTeamIDs(ctx context.Context, cliTeams []string) []string {
|
|
return getLinearTeamIDsForStore(ctx, tracker.NewStore(store), cliTeams)
|
|
}
|
|
|
|
func getLinearTeamIDsForStore(ctx context.Context, st tracker.Store, cliTeams []string) []string {
|
|
pluralVal, _ := getLinearConfigForStore(ctx, st, "linear.team_ids")
|
|
singularVal, _ := getLinearConfigForStore(ctx, st, "linear.team_id")
|
|
return tracker.ResolveProjectIDs(cliTeams, pluralVal, singularVal)
|
|
}
|
|
|
|
// getLinearClient creates a configured Linear client from beads config.
|
|
// Uses the first configured team ID for operations that require a single team.
|
|
//
|
|
// Auth precedence:
|
|
// 1. OAuth env vars (LINEAR_OAUTH_CLIENT_ID + LINEAR_OAUTH_CLIENT_SECRET)
|
|
// 2. LINEAR_API_KEY env var
|
|
// 3. linear.oauth_client_id + linear.oauth_client_secret in config
|
|
// 4. linear.api_key in config
|
|
func getLinearClient(ctx context.Context) (*linear.Client, error) {
|
|
teamIDs := getLinearTeamIDs(ctx, nil)
|
|
if len(teamIDs) == 0 {
|
|
return nil, fmt.Errorf("Linear team ID not configured")
|
|
}
|
|
|
|
client, err := buildLinearClient(ctx, teamIDs[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if store != nil {
|
|
if endpoint, _ := store.GetConfig(ctx, "linear.api_endpoint"); endpoint != "" {
|
|
client = client.WithEndpoint(endpoint)
|
|
}
|
|
if projectID, _ := store.GetConfig(ctx, "linear.project_id"); projectID != "" {
|
|
client = client.WithProjectID(projectID)
|
|
}
|
|
// Apply optional rate-limit circuit-breaker floor.
|
|
// Readable/settable via `bd config get/set linear.rate_limit_floor`.
|
|
// Also honored via the LINEAR_RATE_LIMIT_FLOOR environment variable.
|
|
floorStr, _ := getLinearConfig(ctx, "linear.rate_limit_floor")
|
|
if floorStr == "" {
|
|
floorStr = os.Getenv("LINEAR_RATE_LIMIT_FLOOR")
|
|
}
|
|
if floorStr != "" {
|
|
if v, err := strconv.Atoi(strings.TrimSpace(floorStr)); err == nil && v >= 0 {
|
|
client = client.WithRateLimitFloor(v)
|
|
}
|
|
}
|
|
}
|
|
|
|
return client, nil
|
|
}
|
|
|
|
// buildLinearClient resolves auth credentials and returns an appropriately
|
|
// configured Linear client. OAuth takes precedence over API key.
|
|
func buildLinearClient(ctx context.Context, teamID string) (*linear.Client, error) {
|
|
oauthClientID, _ := getLinearConfig(ctx, "linear.oauth_client_id")
|
|
oauthClientSecret, _ := getLinearConfig(ctx, "linear.oauth_client_secret")
|
|
|
|
if oauthClientID != "" && oauthClientSecret != "" {
|
|
debug.Logf("Linear: using OAuth client-credentials authentication")
|
|
oauthCfg := linear.OAuthConfig{
|
|
ClientID: oauthClientID,
|
|
ClientSecret: oauthClientSecret,
|
|
}
|
|
return linear.NewOAuthClient(oauthCfg, teamID), nil
|
|
}
|
|
|
|
apiKey, _ := getLinearConfig(ctx, "linear.api_key")
|
|
if apiKey == "" {
|
|
return nil, fmt.Errorf("Linear authentication not configured\n" +
|
|
"Options:\n" +
|
|
" OAuth (for CI): export LINEAR_OAUTH_CLIENT_ID=... LINEAR_OAUTH_CLIENT_SECRET=...\n" +
|
|
" API key (devs): export LINEAR_API_KEY=... or bd config set linear.api_key \"...\"")
|
|
}
|
|
|
|
return linear.NewClient(apiKey, teamID), nil
|
|
}
|
|
|
|
func buildLinearClientAPIOnly(ctx context.Context, teamID string, st tracker.Store) (*linear.Client, error) {
|
|
oauthClientID := os.Getenv("LINEAR_OAUTH_CLIENT_ID")
|
|
oauthClientSecret := os.Getenv("LINEAR_OAUTH_CLIENT_SECRET")
|
|
if oauthClientID == "" {
|
|
oauthClientID = config.GetString("linear.oauth_client_id")
|
|
}
|
|
if oauthClientSecret == "" {
|
|
oauthClientSecret = config.GetString("linear.oauth_client_secret")
|
|
}
|
|
// Select the auth branch first and apply linear.api_endpoint once, after
|
|
// it — the shape Tracker.Init uses. Returning the OAuth client inline
|
|
// would leave this helper asymmetric between its own two branches, with a
|
|
// custom endpoint honored for an API key and ignored for OAuth.
|
|
var client *linear.Client
|
|
if oauthClientID != "" && oauthClientSecret != "" {
|
|
client = linear.NewOAuthClient(linear.OAuthConfig{ClientID: oauthClientID, ClientSecret: oauthClientSecret}, teamID)
|
|
} else {
|
|
apiKey := os.Getenv("LINEAR_API_KEY")
|
|
if apiKey == "" {
|
|
apiKey = config.GetString("linear.api_key")
|
|
}
|
|
if apiKey == "" {
|
|
return nil, fmt.Errorf("Linear authentication not configured")
|
|
}
|
|
client = linear.NewClient(apiKey, teamID)
|
|
}
|
|
if st != nil {
|
|
if endpoint, _ := st.GetConfig(ctx, "linear.api_endpoint"); endpoint != "" {
|
|
client = client.WithEndpoint(endpoint)
|
|
}
|
|
}
|
|
return client, nil
|
|
}
|
|
|
|
// storeConfigLoader adapts the store to the linear.ConfigLoader interface.
|
|
type storeConfigLoader struct {
|
|
ctx context.Context
|
|
}
|
|
|
|
func (l *storeConfigLoader) GetAllConfig() (map[string]string, error) {
|
|
return store.GetAllConfig(l.ctx)
|
|
}
|
|
|
|
// loadLinearMappingConfig loads mapping configuration from beads config.
|
|
func loadLinearMappingConfig(ctx context.Context) *linear.MappingConfig {
|
|
if store == nil {
|
|
return linear.DefaultMappingConfig()
|
|
}
|
|
return linear.LoadMappingConfig(&storeConfigLoader{ctx: ctx})
|
|
}
|
|
|
|
// getLinearIDMode returns the configured ID mode for Linear imports.
|
|
// Supported values: "hash" (default) or "db".
|
|
func getLinearIDMode(ctx context.Context) string {
|
|
return getLinearIDModeForStore(ctx, tracker.NewStore(store))
|
|
}
|
|
|
|
func getLinearIDModeForStore(ctx context.Context, st tracker.Store) string {
|
|
mode, _ := getLinearConfigForStore(ctx, st, "linear.id_mode")
|
|
mode = strings.ToLower(strings.TrimSpace(mode))
|
|
if mode == "" {
|
|
return "hash"
|
|
}
|
|
return mode
|
|
}
|
|
|
|
// applyLinearExcludeIDConfig reads linear.exclude_id_prefix and
|
|
// linear.exclude_id_patterns from the given config reader and applies them
|
|
// to opts. Both keys are push-direction-only filters; see the help text on
|
|
// linearSyncCmd for the user-facing semantics.
|
|
//
|
|
// Empty values are no-ops. Patterns are comma-split, trimmed, with empty
|
|
// entries dropped. If reader is nil (no store configured), this is a no-op.
|
|
func applyLinearExcludeIDConfig(ctx context.Context, reader configReader, opts *tracker.SyncOptions) {
|
|
if reader == nil || opts == nil {
|
|
return
|
|
}
|
|
if v, _ := reader.GetConfig(ctx, "linear.exclude_id_prefix"); v != "" {
|
|
opts.ExcludeIDPrefix = strings.TrimSpace(v)
|
|
}
|
|
if v, _ := reader.GetConfig(ctx, "linear.exclude_id_patterns"); v != "" {
|
|
for _, p := range strings.Split(v, ",") {
|
|
p = strings.TrimSpace(p)
|
|
if p != "" {
|
|
opts.ExcludeIDPatterns = append(opts.ExcludeIDPatterns, p)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// getLinearHashLength returns the configured hash length for Linear imports.
|
|
// Values are clamped to the supported range 3-8.
|
|
func getLinearHashLength(ctx context.Context) int {
|
|
return getLinearHashLengthForStore(ctx, tracker.NewStore(store))
|
|
}
|
|
|
|
func getLinearHashLengthForStore(ctx context.Context, st tracker.Store) int {
|
|
raw, _ := getLinearConfigForStore(ctx, st, "linear.hash_length")
|
|
if raw == "" {
|
|
return 6
|
|
}
|
|
value, err := strconv.Atoi(strings.TrimSpace(raw))
|
|
if err != nil {
|
|
return 6
|
|
}
|
|
if value < 3 {
|
|
return 3
|
|
}
|
|
if value > 8 {
|
|
return 8
|
|
}
|
|
return value
|
|
}
|
|
|
|
// syncIsScoped returns true when the user explicitly constrained THIS
|
|
// invocation to a specific subset of beads (via --parent, --issues, or
|
|
// --type). The parent reconcile pass is skipped on scoped syncs because
|
|
// it walks the full local tree, which could mutate Linear-side state
|
|
// outside the scope the user asked for.
|
|
//
|
|
// Notably ExcludeTypes is NOT a scoping signal: it merges with persistent
|
|
// config (linear.exclude_types), and rigs that set it default-on (e.g.
|
|
// "molecule,event") would otherwise have the reconcile pass permanently
|
|
// disabled — bd-9w3 root cause. Reconcile only ever touches the parent
|
|
// field on the child issue, so excluding types from push doesn't really
|
|
// conflict with wiring up parent-child for the remaining types.
|
|
//
|
|
// TypeFilter IS kept as a scoping signal because --type is set only via
|
|
// the CLI flag for this invocation; the user's intent to push a specific
|
|
// subset is explicit.
|
|
func syncIsScoped(opts *tracker.SyncOptions) bool {
|
|
if opts == nil {
|
|
return false
|
|
}
|
|
if opts.ParentID != "" || len(opts.IssueIDs) > 0 {
|
|
return true
|
|
}
|
|
if len(opts.TypeFilter) > 0 {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// reconcileLinearParents runs as a post-sync pass to wire parent-child bead
|
|
// dependencies into Linear's parent issue field. Idempotent — no API call
|
|
// when the remote parent already matches.
|
|
//
|
|
// Two scenarios this fixes:
|
|
//
|
|
// 1. Fresh tree push: when a child is pushed before its parent in the same
|
|
// sync, the create call has no parentId to send. After all issues have
|
|
// external_refs, this pass closes the loop.
|
|
// 2. Orphan repair: existing Linear issues created in earlier bd versions
|
|
// (or by interrupted syncs) without a parent get wired up retroactively.
|
|
//
|
|
// In dry-run mode the read-only fetches still run and the per-link mutation
|
|
// plan is printed as [dry-run] lines, but no IssueUpdate is issued. Lets
|
|
// users preview the orphan-repair scope before committing to a wet sync.
|
|
//
|
|
// Human-readable output is suppressed when jsonOutput is true so the
|
|
// caller's JSON serialization (in runLinearSync's output section) isn't
|
|
// polluted with stray fmt.Printf lines. Warnings and errors still go
|
|
// through the warnings slice, which IS surfaced in JSON output via
|
|
// SyncResult.Warnings.
|
|
//
|
|
// Warnings (per-link failures, missing refs) are appended to the engine's
|
|
// warning slice so the user sees them in the standard sync output.
|
|
func reconcileLinearParents(ctx context.Context, lt *linear.Tracker, dryRun, jsonOutput bool, warnings *[]string) {
|
|
reconcileLinearParentsForStore(ctx, tracker.NewStore(store), lt, dryRun, jsonOutput, warnings)
|
|
}
|
|
|
|
func reconcileLinearParentsForStore(ctx context.Context, st tracker.Store, lt *linear.Tracker, dryRun, jsonOutput bool, warnings *[]string) {
|
|
if lt == nil || st == nil {
|
|
return
|
|
}
|
|
links, err := buildLinearParentLinksForStore(ctx, st, lt)
|
|
if err != nil {
|
|
*warnings = append(*warnings, fmt.Sprintf("parent reconcile: building link set failed: %v", err))
|
|
return
|
|
}
|
|
if len(links) == 0 {
|
|
return
|
|
}
|
|
stats, err := lt.ReconcileParents(ctx, links, dryRun)
|
|
// Print mutation summary first; an abort (e.g. rate-limit circuit
|
|
// breaker) may have completed some updates before bailing, and the
|
|
// user should see that work wasn't lost. Suppress when --json is
|
|
// requested so the JSON envelope stays clean.
|
|
if stats != nil && !jsonOutput {
|
|
if dryRun {
|
|
if stats.WouldUpdate > 0 {
|
|
fmt.Printf("[dry-run] Would reconcile %d Linear parent link%s\n",
|
|
stats.WouldUpdate, plural(stats.WouldUpdate))
|
|
for _, link := range stats.Mutations {
|
|
fmt.Printf("[dry-run] Would set parent of %s → %s\n",
|
|
link.ChildIdentifier, link.ParentIdentifier)
|
|
}
|
|
}
|
|
} else if stats.Updated > 0 {
|
|
fmt.Printf("✓ Reconciled %d Linear parent link%s\n",
|
|
stats.Updated, plural(stats.Updated))
|
|
}
|
|
}
|
|
if err != nil {
|
|
*warnings = append(*warnings, fmt.Sprintf("parent reconcile: %v", err))
|
|
return
|
|
}
|
|
for _, e := range stats.Errors {
|
|
*warnings = append(*warnings, fmt.Sprintf("parent reconcile: %v", e))
|
|
}
|
|
}
|
|
|
|
// buildLinearParentLinks enumerates local beads with a Linear external_ref
|
|
// and a parent-child dependency to a parent that also has a Linear
|
|
// external_ref. The result is the set of (child, parent) pairs whose
|
|
// Linear parent field should be set.
|
|
//
|
|
// Beads whose parent isn't yet synced to Linear are silently skipped —
|
|
// they'll get picked up on a subsequent sync once the parent has an
|
|
// external_ref.
|
|
func buildLinearParentLinks(ctx context.Context, lt *linear.Tracker) ([]linear.ParentLink, error) {
|
|
return buildLinearParentLinksForStore(ctx, tracker.NewStore(store), lt)
|
|
}
|
|
|
|
func buildLinearParentLinksForStore(ctx context.Context, st tracker.Store, lt *linear.Tracker) ([]linear.ParentLink, error) {
|
|
if st == nil {
|
|
return nil, fmt.Errorf("database not available")
|
|
}
|
|
issues, err := st.SearchIssues(ctx, "", types.IssueFilter{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// First pass: build bead_id → linear-identifier index, restricted to
|
|
// beads whose ref looks like a Linear ref.
|
|
idToIdent := make(map[string]string, len(issues))
|
|
for _, issue := range issues {
|
|
if issue.ExternalRef == nil {
|
|
continue
|
|
}
|
|
ref := strings.TrimSpace(*issue.ExternalRef)
|
|
if !lt.IsExternalRef(ref) {
|
|
continue
|
|
}
|
|
ident := lt.ExtractIdentifier(ref)
|
|
if ident == "" {
|
|
continue
|
|
}
|
|
idToIdent[issue.ID] = ident
|
|
}
|
|
if len(idToIdent) == 0 {
|
|
return nil, nil
|
|
}
|
|
// Second pass: walk each child-bead's dependencies, find the
|
|
// parent-child edge, and emit a link if both ends are Linear-synced.
|
|
links := make([]linear.ParentLink, 0)
|
|
for _, issue := range issues {
|
|
childIdent, ok := idToIdent[issue.ID]
|
|
if !ok {
|
|
continue
|
|
}
|
|
deps, err := st.GetDependenciesWithMetadata(ctx, issue.ID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("loading deps for %s: %w", issue.ID, err)
|
|
}
|
|
for _, d := range deps {
|
|
if d == nil || d.DependencyType != types.DepParentChild {
|
|
continue
|
|
}
|
|
// child depends-on parent — the dep target's embedded Issue is the parent.
|
|
parentIdent, ok := idToIdent[d.Issue.ID]
|
|
if !ok {
|
|
continue
|
|
}
|
|
links = append(links, linear.ParentLink{
|
|
ChildIdentifier: childIdent,
|
|
ParentIdentifier: parentIdent,
|
|
})
|
|
}
|
|
}
|
|
return links, nil
|
|
}
|
|
|
|
func plural(n int) string {
|
|
if n == 1 {
|
|
return ""
|
|
}
|
|
return "s"
|
|
}
|