* feat(storage): be-x42v.1 BEADS_MAX_ROWS defensive cap foundation Add IssueFilter.MaxRows + IssueFilter.MaxRowsSource and a typed issueops.ErrTooManyRows error. searchTableInTx routes its LIMIT through EffectiveSearchLimit (LIMIT MaxRows+1 when MaxRows>0, with Limit preserved otherwise); SearchIssuesInTx checks EnforceMaxRowsCap after the issues+wisps merge so the cap reflects the count returned to the caller. Both helpers are exported so future PG-backend support can reuse the same logic. Default MaxRows=0 disables the cap and is byte-identical to today at every existing call site. Limit semantics are unchanged: Limit=0 still means unlimited at the contract level. PG backend is not on origin/main yet; PG cap support is a follow-up when the postgres backend merges. Validator's per-backend bead exercises the issueops path via Dolt/embedded fixtures. Refs: be-x42v (designer §3/§6.2), be-jp5s (architecture D1/R-03). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(cli): be-x42v.2 wire --max-rows / BEADS_MAX_ROWS on CLI surface Adds cmd/bd/max_rows.go with three helpers: addMaxRowsFlag registers --max-rows int with the designer's spec help text, resolveMaxRows picks flag > env > 0 (negative flag → exit 1, bad env → warn-and-ignore), and handleMaxRowsError pattern-matches *issueops.ErrTooManyRows to emit the two-line stderr message and exit 2 with stdout empty. The flag is wired on bd list, bd ready, bd dep tree, bd find-duplicates, and bd graph (designer §4). The env-only resolveMaxRowsEnvOnly variant is wired on bd lint and the SearchIssues paths inside bd doctor (conventions + pollution checks). bd cleanup, bd gc, bd export, bd export --auto, bd migrate-issues, and bd jira explicitly set MaxRows=0 / MaxRowsSource="" in code so a misconfigured env can't abort a data-integrity sweep partway through. bd ready needed storage-layer support too: WorkFilter gains MaxRows + MaxRowsSource and GetReadyWorkInTx routes its LIMIT through EffectiveSearchLimit and enforces the cap via EnforceMaxRowsCap on the row count returned to the caller. bd dep tree applies the cap at the CLI layer on the TreeNode count since the tree walk doesn't go through IssueFilter. bd config show gains a standalone-env collector so BEADS_MAX_ROWS shows up alongside BEADS_DIR etc. when set. The Viper-managed env detection skips it because BEADS_MAX_ROWS isn't bound to a config key. Adds a CONTRIBUTING.md section documenting the opt-out rule for new IssueFilter sites that aren't on designer §4's wired-up list, with a pointer to the validator's opt-out test gates (be-x42v.4). Smoke-tested against the rig database (298 issues): - bd list --max-rows 5 → exit 2, "--max-rows=5" - BEADS_MAX_ROWS=5 bd list → exit 2, "BEADS_MAX_ROWS=5" - BEADS_MAX_ROWS=banana bd list --limit 3 → warn + exit 0 - BEADS_MAX_ROWS=5 bd list --max-rows 0 --limit 3 → exit 0 - bd list --max-rows -1 → exit 1, "must be non-negative" - bd ready --max-rows 5 → exit 2 (storage layer fires) - bd dep tree be-jp5s --max-rows 1 → exit 2 (CLI-layer count) - bd find-duplicates --max-rows 5 → exit 2 - bd graph --all --max-rows 5 → exit 2 - BEADS_MAX_ROWS=5 bd lint → exit 2 (env-only) - BEADS_MAX_ROWS=5 bd export → exit 0, 299 lines (opt-out) - BEADS_MAX_ROWS=10 bd config show → lists BEADS_MAX_ROWS The 10 CLI behavioral test scenarios for bd list are owned by be-x42v.3 (validator). Coverage for the non-list paths, the env-only doctor family, and config show is filed as be-u8z9 (needs-tests, routed to validator). Refs: be-x42v (designer §2-§5), be-x42v.1 (foundation). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: release gate PASS for be-x42v.1 + be-x42v.2 (BEADS_MAX_ROWS) Documents PASS evaluation across the six gate criteria for the storage foundation (be-x42v.1, 3900c1bdc) and the CLI wiring (be-x42v.2, dea537c56) shipping together. Review verdicts: be-xf0o (foundation) and be-2p12 (CLI), both PASS from Opus 4.7 reviewer. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: regenerate CLI reference for --max-rows flag * docs: revert federation to pure-go stub in CLI_REFERENCE.md CI's check-doc-flags freshness check runs generate-cli-docs.sh with CGO_ENABLED=0. The previous regeneration used a CGO binary, expanding the federation section with subcommands. Revert to the requires-CGO stub that the pure-go binary produces. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * docs: revert website federation.md pages to pure-go stub (be-x42v) Three website cli-reference/federation.md files still had CGO-enabled content after CLI_REFERENCE.md was reverted. This commit brings them into sync with the pure-go stub, resolving the Check doc flags freshness CI failure on PR #3908. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(cli): be-u8z9 BEADS_MAX_ROWS non-list command paths + config show Locks down the manually-verified behavior shipped in be-x42v.2 across the CLI surface beyond `bd list`. cmd/bd/max_rows_test.go (new): - ReadyMaxRows_FlagOverCap_Exits2 - bd ready --max-rows N → exit 2 - ReadyMaxRows_EnvOverCap_Exits2 - BEADS_MAX_ROWS=N bd ready → exit 2 - DepTreeMaxRows_TreeNodes_Exits2 - tree-node count cap in dep tree - FindDuplicatesMaxRows_Exits2 - find-duplicates --max-rows N - GraphAllMaxRows_Exits2 - graph --all --max-rows N - LintMaxRows_EnvOnly_Exits2 - bd lint with BEADS_MAX_ROWS=N - LintMaxRows_NoFlagAccepted - cobra rejects --max-rows on lint - ConfigShow_ListsBeadsMaxRows - bd config show surfaces the env var - ConventionsMaxRows_EnvOnly - skipped (bd doctor needs server mode, follow-up filed as be-pc8c) - PollutionMaxRows_EnvOnly - skipped (same reason) cmd/bd/ready_max_rows_test.go (new): - TestGetReadyWork_MaxRowsSuite — exercises WorkFilter.MaxRows in GetReadyWork (under cap / over cap / zero disabled / with Limit matrix), via newTestStore. Companion to the SearchIssues parity work in be-x42v.3. Refs: be-u8z9 (this bead), be-x42v.2 (builder), be-pc8c (follow-up). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(cli,storage): be-x42v.3 BEADS_MAX_ROWS bd list scenarios + backend parity Covers the 10 CLI scenarios from designer §6.1 against `bd list` and the 5 storage scenarios from designer §6.2 against both Dolt-server and embedded backends. cmd/bd/max_rows_test.go (extended): TestEmbeddedMaxRowsList — 10 subtests on a shared 21-issue rig: - Disabled_NoEnv (baseline, no cap) - Flag_UnderCap (--max-rows 100 over 21 rows → success) - Flag_OverCap (--max-rows 5 → exit 2, source attribution, empty stdout) - Env_OverCap (BEADS_MAX_ROWS=5 → exit 2, env source) - Flag_OverridesEnv (env=5 flag=100 → success) - Flag_Zero_OverridesEnv (env=5 --max-rows 0 → success, explicit disable) - BadEnv_LogsAndIgnores (env=banana → warning + normal output, exit 0) - Negative_FlagRejected (--max-rows -1 → "must be non-negative", exit 1) - LimitSet_CapTighter (--limit 100 --max-rows 5 → exit 2) - LimitSet_CapLooser (--limit 5 --max-rows 100 → 5 rows, exit 0) internal/storage/embeddeddolt/search_max_rows_test.go (new): TestSearchIssues_MaxRows_{NotExceeded,Exceeded,Zero_NoCap,WithLimit} Exercises SearchIssues end-to-end against the embedded backend on a 6-row fixture, including the four-quadrant (Limit, MaxRows) matrix. internal/storage/dolt/search_max_rows_test.go (new): Identical scenarios against the dolt-server backend. Per-backend parity is implicit: both SearchIssues entry points wrap issueops.SearchIssuesInTx, so cap behavior is shared by construction. Same fixture + same assertions ensures divergence cannot ship silently. PG backend coverage is deferred until the postgres-backend branch lands (per PR #3908 description and parent designer notes). Refs: be-x42v.3 (this bead), be-x42v.2 (builder), be-u8z9 (sibling validator for non-list paths). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(cli): be-x42v.4 opt-out gate tests for data-integrity commands Add filterCapturingStore spy and four MaxRows=0 gate tests asserting that bd export, bd export --auto, bd jira sync, and bd migrate-issues always construct IssueFilter with MaxRows=0 / MaxRowsSource="" per designer §4.1 opt-out rule. A BEADS_MAX_ROWS env var on these paths would corrupt backups, sync state, or migration runs mid-flight. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(cli): be-x42v.4 add TestExport_BypassesBeadsMaxRows behavioral gate End-to-end belt-and-suspenders test (designer §6.4): sets BEADS_MAX_ROWS=1, seeds 5 task issues, runs runExport, and asserts 5 JSONL lines in the output. Completes the be-x42v.4 acceptance criteria for the bypass behavioral test alongside the filter-spy gate already committed. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(cli): be-pc8c server-mode BEADS_MAX_ROWS gate for bd doctor --check={conventions,pollution} TestDoctorConventionsMaxRows_EnvOnly_Exits2 and TestDoctorPollutionMaxRows_EnvOnly_Exits2 cover the two subtests that were skipped in max_rows_test.go because bd doctor refuses to run in embedded mode (doctor.go:188). Both tests seed 6 open issues against the Dolt test server with BEADS_MAX_ROWS=3, assert exit 2, and confirm BEADS_MAX_ROWS=3 in the combined output. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(search): enforce MaxRows cap when wisps table is empty SearchIssuesInTx skipped EnforceMaxRowsCap on the common empty-wisps path: when filter.Ephemeral is nil/false and the wisps table is empty, the early `return results, nil` returned before the post-merge cap check. The issues-only result set (LIMIT cap+1) could exceed MaxRows yet never trip ErrTooManyRows. Enforce the cap before the early return. Fixes TestSearchIssues_MaxRows_Exceeded_ReturnsErrTooManyRows and TestSearchIssues_MaxRows_WithLimit (internal/storage/embeddeddolt). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(rebase): re-home BEADS_MAX_ROWS enforcement onto post-rebase seams Fixes gaps exposed by rebasing PR #4160 onto current upstream/main, found by actually running the PR's own gate tests rather than just resolving textual conflicts: - internal/storage/issueops/search.go: the Q2 perf-escape-hatch SkipWisps early return (added by main's search perf work, landed after this PR's original design) skipped EnforceMaxRowsCap entirely. bd list sets SkipWisps=true by default, so `bd list --max-rows N` silently ignored the cap. Enforce the cap on that return path too, mirroring the existing empty-wisps-table fix alongside it. - internal/storage/issueops/search_counts.go: SearchIssuesWithCountsInTx (the `--json` query path, already present at the PR's merge-base but never wired for MaxRows by the original be-x42v.1/.2 commits) neither sized its SQL LIMIT off the cap nor enforced it on the merged result. Thread filter.MaxRows through EffectiveSearchLimit for the query LIMIT and check EnforceMaxRowsCap in the shared finishSearchIssuesWithCounts terminal helper (now returns an error), which every exit path already routed through. Fixes be-x42v.3's TestEmbeddedMaxRowsList/Flag_OverCap (`bd list --json --max-rows 5`), which failed after the rebase. - cmd/bd/jira_max_rows_gate_test.go, cmd/bd/migrate_issues_max_rows_gate_test.go: seed INSERTs predate migration 0049 (LONGTEXT NOT NULL on issues.description/design/ acceptance_criteria/notes, no default) that landed on main after this branch's merge-base. Provide empty-string values for the now-required columns. Not fixed (separate, pre-existing gap; no gate test in this PR exercises it): GetReadyWorkWithCountsInTx (`bd ready --json` / `bd list --ready --json`) also doesn't thread MaxRows. Left alone to keep this rebase to conflict resolution rather than expanding scope; worth a follow-up bead. Agent-Signature: claude-sonnet-medium on behalf of maphew * fix(review): address adjudicated cross-vendor review follow-up (be-x42v.4) Works the MUST-FIX / SHOULD-FIX list from the adjudicated claude-opus + codex-gpt-5.6-sol review on the rebase (25e35cc3e), landing coverage gaps the vendors found in the feature's own promise rather than the rebase mechanics. MUST-FIX: 1. internal/storage/issueops/claim.go: ClaimReadyIssueInTx forwarded the caller's MaxRows/MaxRowsSource into its internal unbounded GetReadyWorkInTx scan, so a rig-wide cap (e.g. BEADS_MAX_ROWS=100 with 150 ready issues) hard-failed a claim that only ever consumes one row. Bound the internal scan via Limit instead, then clear the cap fields. 2. cmd/bd/ready.go, internal/storage/issueops/ready_work_counts.go: GetReadyWorkWithCountsInTx (ready --json / list --ready --json) never enforced MaxRows at all — a pre-existing gap in the original PR (the function predates this branch's merge-base), not something the rebase introduced. Threaded EffectiveSearchLimit into its query LIMIT and added EnforceMaxRowsCap via a new finishReadyWorkWithCounts terminal helper, mirroring finishSearchIssuesWithCounts. Wired handleMaxRowsError on the bd ready --json error branch. 3. cmd/bd/max_rows.go + list/ready/graph/dep/find-duplicates: proxied-server mode silently ignored the cap (the proxied repository doesn't thread MaxRows through the UOW pipeline). Added rejectMaxRowsUnderProxiedServer, called on every command that registers --max-rows before it diverts to its *ProxiedServer path — an explicit --max-rows or BEADS_MAX_ROWS now errors out under --proxied-server instead of no-oping. 4. cmd/bd/list.go: `--limit N --max-rows N` errored instead of truncating. withFetchOneExtra unconditionally bumped Limit to N+1 for its own >N-matches truncation-hint probe, which then crossed EffectiveSearchLimit's `limit > maxRows` branch and tripped the cap on the probe row alone, even though the delivered set is always trimmed back to N. withFetchOneExtra now skips the bump when MaxRows is active and no looser than Limit; >N-matches semantics for limit<maxRows are unaffected. 5. cmd/bd/list.go: `bd list --watch` swallowed the initial-query cap error (logged to stderr, returned void, exited 0). watchIssues now returns the initial-query error instead of handling it itself; runListCore routes it through handleMaxRowsError for exit-code-2 semantics. Mid-poll refresh failures still just log and continue (interactive command, not a reason to kill the watch loop). 6. cmd/bd/max_rows.go + every call site: handleMaxRowsError and the --max-rows usage-error path in resolveMaxRows called os.Exit directly from deep inside RunE, bypassing both the command's own metrics defer and main()'s post-ExecuteC metrics.CloseAndFlush(). Converted both to return errors: resolveMaxRows now returns (int, string, error) and handleMaxRowsError returns error, both following the exact &exitError{Code: N}-via-RunE precedent already used elsewhere in this package (e.g. list_input.go's skip-labels-conflict check, HandleErrorRespectJSON). doctor_conventions.go's runConventionsLint (called from a "() []doctorCheck" advisory-checks aggregator with no error channel) needed its own (([]doctorCheck, error) signature to propagate the one non-advisory failure mode; every other call site was already RunE-adjacent. SHOULD-FIX (both mechanical, done): 7. cmd/bd/graph.go: `bd graph <issue>` (no --all) never resolved the cap. loadGraphSubgraph is a BFS over per-ID GetDependents/GetDependencies lookups with no IssueFilter to thread MaxRows through, so — mirroring dep tree — the cap is now checked post-hoc against the final connected-component node count. Documented both graph's per-status (--all) and post-hoc (single-issue) cap semantics, and dep tree's post-hoc semantics, in their flag help text. 8. internal/storage/issueops/ready_work.go: getReadyWispsInTx's unbounded (Limit<=0) branch queried and hydrated the *entire* wisps table before the post-merge cap check in GetReadyWorkInTx ever ran, defeating the "circuit breaker against pathological queries" purpose for --include-ephemeral. readyWorkWispIssueFilter now propagates MaxRows/MaxRowsSource so EffectiveSearchLimit bounds that query to cap+1 up front. Tests added: TestClaimReadyIssue_MaxRows_LargePoolUnderLowCap (1), ReadyMaxRowsJSON_FlagOverCap_Exits2 + ListReadyMaxRowsJSON_FlagOverCap_Exits2 (2), reject_max_rows_flag + reject_max_rows_env + allow_max_rows_zero under TestProxiedServerList (3), LimitEqualsCap_TruncatesNotErrors + LimitEqualsCap_JSON_TruncatesNotErrors (4), Watch_FlagOverCap_Exits2 (5), GraphSingleIssueMaxRows_NodeCount_Exits2 + _UnderCap_NoError (7), ReadyIncludeEphemeralMaxRows_FlagOverCap_Exits2 (8). Verified: go build/vet clean; full MaxRows-named + FilterHasZeroMaxRows + BypassesBeadsMaxRows sweep passes in both dolt-server and BEADS_TEST_EMBEDDED_DOLT=1 modes (one dolt-testcontainer flake observed and confirmed non-reproducing on retry, consistent with prior sessions); TestProxiedServerList passes with BEADS_TEST_PROXIED_SERVER=1. Agent-Signature: claude-sonnet-medium on behalf of maphew * fix(review): address round-2 delta review regressions (be-x42v.4 round 3) opus verified all eight round-2 items as implemented, but codex found three regressions those fixes introduced, confirmed on adjudication. Common thread: enforce the cap on the DELIVERED result, not on fetched/merged intermediates, and don't let the safety rejection block one-row operations. 1. cmd/bd/ready.go: proxied `bd ready --claim` was rejected by rejectMaxRowsUnderProxiedServer before it could dispatch to runReadyProxiedClaim, even though --claim always delivers exactly one row and the direct-path fix (claim.go, round 2) already exempts claim from cap enforcement for that exact reason. Moved the claimReady flag parse before the proxied branch and exempt --claim from the rejection; bulk (non-claim) proxied `bd ready` still rejects an active cap. Added claim_succeeds_under_env_max_rows_cap plus reject_bulk_ready_under_max_rows_{flag,env} to ready_proxied_integration_test.go. 2. internal/storage/issueops/ready_work_counts.go: with --include-ephemeral, GetReadyWorkWithCountsInTx's issues and wisps queries are each independently bounded by EffectiveSearchLimit(filter.Limit, filter.MaxRows), so the merged pre-trim slice can hold up to ~2x that per-table bound even when filter.Limit <= filter.MaxRows (e.g. limit=2, cap=3, 2 rows/table -> merged 4 -> false "too many rows" even though the delivered page, trimmed to 2, is well within the cap). Reordered finishReadyWorkWithCounts to trim to Limit before checking the cap, mirroring GetReadyWorkInTx's non-counts path (mergeReadyWisps already trims before its caller's EnforceMaxRowsCap runs). Verified this reproduces "4 found, --max-rows=3 exceeded" on the pre-fix code and is fixed after. Added ReadyIncludeEphemeralMaxRowsJSON_MergedUnderLimit_NoError. 3. cmd/bd/list.go: round-2's fix for `--limit N --max-rows N` (skip the withFetchOneExtra probe-row bump entirely when Limit>=MaxRows) stopped the false cap error but also stopped fetching the extra row, so len(results) could never exceed effectiveLimit and the GH#3212 truncation notice silently stopped firing — a partial result started presenting as complete. Restored the probe-row fetch (Limit still bumps to N+1) and instead bump MaxRows to N+1 in lockstep, but only in the exact Limit==MaxRows case: this keeps the probe row inside the (temporarily N+1) cap so EnforceMaxRowsCap doesn't trip on it, while the CLI's own len(results)>effectiveLimit check still sees the extra row and correctly reports truncated=true. Tighter-cap (Limit>MaxRows) and looser-cap (Limit<MaxRows) cases are unaffected — MaxRows is left unbumped there, so a genuine violation still reports the true cap value. printTruncationHint's text is gated on ui.IsStderrTerminal() and unconditionally suppressed for this subprocess test harness's piped stderr (matches the existing limit_truncation_hint subtest's documented constraint), so the fix is verified via 4 new unit tests asserting withFetchOneExtra's exact bump values directly (TestWithFetchOneExtra_LimitEqualsCap_BumpsBothForTruncationProbe et al.) rather than the unobservable hint text; extended LimitEqualsCap_TruncatesNotErrors's comment to document this and point to the unit tests. Opus nits: 4. internal/storage/issueops/claim.go: bounding the claim scan at Limit=MaxRows (round 2) meant a BEADS_MAX_ROWS=1 rig would only attempt the single top-of-queue ready row and return "nothing to claim" if it was transiently unclaimable (e.g. a race with another agent), even with plenty of other ready work available. Restored the unbounded scan (Limit=0); the breaker's job is to bound delivered payloads, and a claim's payload is always exactly one row regardless of scan size. 5. cmd/bd/find_duplicates.go: replaced the inlined proxied-server rejection check with a call to rejectMaxRowsUnderProxiedServer so the message can't drift from the other 4 commands that use it. Verified: go build/vet clean; full MaxRows-named + FilterHasZeroMaxRows + BypassesBeadsMaxRows + WithFetchOneExtra sweep passes in both dolt-server and BEADS_TEST_EMBEDDED_DOLT=1 modes; TestProxiedServerList + TestProxiedServerReady (full suites, ~200s) pass with BEADS_TEST_PROXIED_SERVER=1; broader TestList|TestWatch|TestGraph| TestDepTree|TestReady|TestClaim|TestFindDuplicates sweep clean except the same pre-existing unrelated ICU-header build failure noted in the round-2 commit (confirmed via stash-based control test to reproduce identically without this round's changes). Agent-Signature: claude-sonnet-medium on behalf of maphew * fix(review): address round-3 delta review items (be-x42v.4 round 4) Converging: four small items adjudicated from round-3 delta reviews. 1. internal/storage/issueops/search.go, search_counts.go: round 3's trim-before-cap fix landed in finishReadyWorkWithCounts but not on the sibling bd list search paths. `bd list --include-infra --limit 2 --max-rows 5` (3 durable + 3 wisps) exited 2 in both output modes even though the delivered page is 2 rows, since --include-infra disables the default SkipWisps escape hatch so the wisps merge actually runs. Reproduced live: "6 found, --max-rows=5 exceeded" on the pre-fix code. Mirrored the ready remedy: trim to filter.Limit (guarded by Limit>0) before EnforceMaxRowsCap in searchInTx's four exit points (added a trimToSearchLimit helper) and in finishSearchIssuesWithCounts (swapped the cap/trim order). Fixed search_counts.go's doc comment, which still asserted the old cap-before-trim rationale and directly contradicted ready_work_counts.go's. Single-source results are unaffected (a lone query never exceeds Limit when Limit>0, so the trim there is a no-op); Limit=0 and genuine Limit>MaxRows overage still error. Added IncludeInfraMergedUnderLimit_NoError (both bd list output modes) to TestEmbeddedMaxRowsList. 2. cmd/bd/ready.go: the round-3 fix that exempts proxied `ready --claim` from rejectMaxRowsUnderProxiedServer also skipped resolveMaxRows entirely for that branch, so `--max-rows -1` was silently accepted under proxied claim (every other command, direct or proxied, rejects it with exit 1). Still call resolveMaxRows in the claim-exempt branch for its validation side effect, ignoring the resolved cap for the claim itself. Reproduced live (claim succeeded instead of failing) on the pre-fix code. Added claim_rejects_invalid_max_rows_flag to ready_proxied_integration_test.go. 3. cmd/bd/find_duplicates.go, cmd/bd/max_rows.go: find-duplicates resolved --max-rows twice under proxied mode (once to build its filter, again inside rejectMaxRowsUnderProxiedServer), doubling the malformed-env stderr warning. Split rejectMaxRowsUnderProxiedServer into itself plus a new rejectResolvedMaxRowsUnderProxiedServer(maxRows int) that takes an already-resolved value; find_duplicates.go now calls the latter with its existing resolved maxRows instead of re-resolving. 4. internal/storage/issueops/claim.go: added a comment sentence noting the unbounded-scan trade-off per the adjudication note — parity with pre-PR main and correctness-first (preserves claim's existing fairness/ordering across the ready set); a bounded, paged scan is a deliberate follow-up, not folded in here. Verified: go build/vet clean; full MaxRows-named + FilterHasZeroMaxRows + BypassesBeadsMaxRows + WithFetchOneExtra sweep passes in both dolt-server and BEADS_TEST_EMBEDDED_DOLT=1 modes (including the two new regression tests); full TestProxiedServerReady suite (~211s) passes with BEADS_TEST_PROXIED_SERVER=1; internal/storage/issueops unit tests pass; broader TestList|TestWatch|TestGraph|TestDepTree|TestReady|TestClaim| TestFindDuplicates sweep clean except the same pre-existing unrelated ICU-header build failure noted in prior rounds. Both new regression tests (item 1 and item 2) reproduce the reported failure on the pre-fix code via git-stash and pass after. Agent-Signature: claude-sonnet-medium on behalf of maphew * fix(review): sort merged issues+wisps before trim in searchInTx (be-x42v.4 round 5) codex P1, confirmed live: searchInTx's merge branch concatenates two independently ORDER BY'd legs (`results = append(filtered, wispResults...)`), and round-4's trimToSearchLimit then sliced that UNSORTED concatenation. With Limit=N and durable rows alone filling N, a higher-ranked wisp (per filter.SortBy/SortDesc) was silently dropped from the page — before round 4 the CLI received the full merged set and its own sort-then-trim produced correct page membership; round 4 moved a naive prefix-trim into storage ahead of any global re-sort. Fix: added a `less func(a, b T, sortBy string, sortDesc bool) bool` field to searchProjection[T], populated for issueProjection via sqlbuild.Less (the existing Go-side mirror of the SQL ORDER BY, already used correctly by search_counts.go's sortSearchIssuesWithCounts). searchInTx's merge branch now re-sorts the concatenation via a new sortMergedResults helper before trimToSearchLimit runs, mirroring how finishSearchIssuesWithCounts already orders before its own trim. idProjection (bare-ID search, no sortable payload) leaves less nil — sortMergedResults no-ops in that case; documented why this is safe today (no current caller combines Limit>0 with a merged, non-SkipWisps ID-only search — see id_parser.go, which always passes Limit=0) and where to look if that changes. The other three trimToSearchLimit call sites in searchInTx are single-source (already SQL-ordered), so they don't need this. Checked the two round-3/round-4-cited "mirror" precedents per the adjudication note, since this bug's shape (unsorted-concat-then-trim) could plausibly recur there: GetReadyWorkInTx's mergeReadyWisps already calls sortReadyIssues(kept, filter.SortPolicy) before its own Limit trim, and GetReadyWorkWithCountsInTx / SearchIssuesWithCountsInTx both already sort (sortIssuesWithCountsByPolicy / sortSearchIssuesWithCounts) before their finish* trim-then-cap helpers. All three were already globally ordered before trimming; only searchInTx had the bug. Added IncludeInfraMerged_WispOutranksDurable_InDeliveredPage to TestEmbeddedMaxRowsList: 3 durable P2 issues + 1 wisp at P0 (outranks under the default priority-ASC sort), --limit 1 in both bd list output modes — asserts the P0 wisp is the delivered row, not an arbitrary P2 durable row. Reproduces exactly against77227aa67(the durable row is returned instead of the wisp) and passes after the fix. Verified: go build/vet clean; full MaxRows-named + FilterHasZeroMaxRows + BypassesBeadsMaxRows + WithFetchOneExtra + Search sweep passes in both dolt-server and BEADS_TEST_EMBEDDED_DOLT=1 modes (including the new regression test); internal/storage/issueops unit tests pass. Agent-Signature: claude-sonnet-medium on behalf of matt wilkie * docs: remove --max-rows lines from pinned-generator CLI docs (be-x42v.4 CI fix) CI's "Check doc flags freshness" job compares docs/CLI_REFERENCE.md and docs/cli-reference/*.md against bd built from the pin in docs/cli-docs.pin (v1.1.0), which predates --max-rows/BEADS_MAX_ROWS — the same pinned-doc-generator trap that hit PRs 3920 and 4022 in this sweep. Any doc lines this PR added for the new flag are flagged stale against that older pinned build, and the failure cascades into "PR Policy (wrapper timing)" via make ci-pr-policy. Applied CI's own generated fix verbatim (downloaded the cli-docs-freshness-patch artifact from the failing job https://github.com/gastownhall/beads/actions/runs/30067827283/job/89403539322, git apply --check passed cleanly, applied as-is — no manual edits). Removes the six --max-rows generated-doc lines (bd list, bd ready, bd dep tree, bd find-duplicates, bd graph — CLI_REFERENCE.md and the matching cli-reference/*.md) plus the incidental column-width realignment in the bd graph flag tables that removing the widest flag name triggers. The flag help strings themselves (cmd/bd/max_rows.go's addMaxRowsFlag) are untouched — those are the source of truth for docs generation and will regenerate correctly once docs/cli-docs.pin advances past this PR's merge. This is a pinned-generator artifact of the CI pipeline, not a statement that the flag is undocumented. Agent-Signature: claude-sonnet-medium on behalf of maphew --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: matt wilkie <maphew@gmail.com>
1293 lines
37 KiB
Go
1293 lines
37 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/storage/issueops"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
)
|
|
|
|
// GraphNode represents a node in the rendered graph
|
|
type GraphNode struct {
|
|
Issue *types.Issue
|
|
Layer int // Horizontal layer (topological order)
|
|
Position int // Vertical position within layer
|
|
DependsOn []string // IDs this node depends on (blocks dependencies only)
|
|
}
|
|
|
|
// GraphLayout holds the computed graph layout
|
|
type GraphLayout struct {
|
|
Nodes map[string]*GraphNode
|
|
Layers [][]string // Layer index -> node IDs in that layer
|
|
MaxLayer int
|
|
RootID string
|
|
}
|
|
|
|
var (
|
|
graphCompact bool
|
|
graphBox bool
|
|
graphAll bool
|
|
graphDOT bool
|
|
graphHTML bool
|
|
graphOpen bool
|
|
)
|
|
|
|
var graphCmd = &cobra.Command{
|
|
Use: "graph [issue-id]",
|
|
GroupID: "deps",
|
|
Short: "Display issue dependency graph",
|
|
Long: `Display a visualization of an issue's dependency graph.
|
|
|
|
For epics, shows all children and their dependencies.
|
|
For regular issues, shows the issue and its direct dependencies.
|
|
|
|
With --all, shows all open issues grouped by connected component.
|
|
With --open, filters to only open/actionable issues (compact layer format).
|
|
|
|
Display formats:
|
|
(default) DAG with columns and box-drawing edges (terminal-native)
|
|
--box ASCII boxes showing layers, more detailed
|
|
--compact Tree format, one line per issue, more scannable
|
|
--dot Graphviz DOT format (pipe to dot -Tsvg > graph.svg)
|
|
--html Self-contained interactive HTML with D3.js visualization
|
|
--open Open issues only, compact layers (LLM-friendly)
|
|
|
|
The graph shows execution order:
|
|
- Layer 0 / leftmost = no dependencies (can start immediately)
|
|
- Higher layers depend on lower layers
|
|
- Nodes in the same layer can run in parallel
|
|
|
|
Status icons: ○ open ◐ in_progress ● blocked ✓ closed ❄ deferred
|
|
|
|
Examples:
|
|
bd graph issue-id # Terminal DAG visualization (default)
|
|
bd graph --box issue-id # ASCII boxes with layer grouping
|
|
bd graph --dot issue-id | dot -Tsvg > graph.svg # SVG via Graphviz
|
|
bd graph --dot issue-id | dot -Tpng > graph.png # PNG via Graphviz
|
|
bd graph --html issue-id > graph.html # Interactive browser view
|
|
bd graph --all --html > all.html # All issues, interactive
|
|
bd graph --open issue-id # Open issues only, layered by blocking order
|
|
bd graph --all --open # All open issues, compact layers
|
|
|
|
--max-rows / BEADS_MAX_ROWS caveat: the cap is checked differently per mode.
|
|
Single-issue graphs (no --all) check the connected-component node count
|
|
after the BFS traversal completes — the whole subgraph is always walked
|
|
first, then rejected if it's over cap. --all checks each status
|
|
(open/in_progress/blocked) independently, so up to 3x the cap can be loaded
|
|
in total before any individual status trips it.`,
|
|
Args: cobra.RangeArgs(0, 1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("graph")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if graphAll && len(args) > 0 {
|
|
return HandleErrorRespectJSON("cannot specify issue ID with --all flag")
|
|
}
|
|
if !graphAll && len(args) == 0 {
|
|
return HandleErrorWithHintRespectJSON("issue ID required", "Use --all for all open issues")
|
|
}
|
|
|
|
if usesProxiedServer() {
|
|
if err := rejectMaxRowsUnderProxiedServer(cmd); err != nil {
|
|
return err
|
|
}
|
|
return runGraphProxiedServer(rootCtx, args)
|
|
}
|
|
|
|
ctx := rootCtx
|
|
if store == nil {
|
|
return HandleErrorRespectJSON("no database connection")
|
|
}
|
|
|
|
if graphAll {
|
|
maxRows, maxRowsSource, err := resolveMaxRows(cmd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
subgraphs, err := loadAllGraphSubgraphs(ctx, store, maxRows, maxRowsSource)
|
|
if err != nil {
|
|
if capErr := handleMaxRowsError(err); capErr != nil {
|
|
return capErr
|
|
}
|
|
return HandleErrorRespectJSON("loading all issues: %v", err)
|
|
}
|
|
return renderGraphAllSubgraphs(subgraphs)
|
|
}
|
|
|
|
issueID, err := utils.ResolvePartialID(ctx, store, args[0])
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("issue '%s' not found", args[0])
|
|
}
|
|
|
|
subgraph, err := loadGraphSubgraph(ctx, store, issueID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("loading graph: %v", err)
|
|
}
|
|
|
|
// Apply the defensive row cap (be-x42v) on the connected-component
|
|
// node count. loadGraphSubgraph is a BFS over GetDependents/
|
|
// GetDependencies (per-ID lookups, no IssueFilter to thread MaxRows
|
|
// through), so — like `bd dep tree` — the cap is checked post-hoc
|
|
// against the final node set rather than during traversal.
|
|
graphMaxRows, graphMaxRowsSource, err := resolveMaxRows(cmd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if graphMaxRows > 0 && len(subgraph.Issues) > graphMaxRows {
|
|
if capErr := handleMaxRowsError(&issueops.ErrTooManyRows{
|
|
Found: len(subgraph.Issues),
|
|
Cap: graphMaxRows,
|
|
Source: graphMaxRowsSource,
|
|
}); capErr != nil {
|
|
return capErr
|
|
}
|
|
}
|
|
|
|
return renderGraphSingleSubgraph(subgraph)
|
|
},
|
|
}
|
|
|
|
func renderGraphAllSubgraphs(subgraphs []*TemplateSubgraph) error {
|
|
if graphOpen {
|
|
var filtered []*TemplateSubgraph
|
|
for _, sg := range subgraphs {
|
|
f := filterSubgraphOpen(sg)
|
|
if f != nil && len(f.Issues) > 0 {
|
|
filtered = append(filtered, f)
|
|
}
|
|
}
|
|
subgraphs = filtered
|
|
}
|
|
|
|
if len(subgraphs) == 0 {
|
|
fmt.Println("No open issues found")
|
|
return nil
|
|
}
|
|
|
|
if jsonOutput {
|
|
return outputJSON(subgraphs)
|
|
}
|
|
|
|
if graphHTML && !graphOpen {
|
|
merged := mergeSubgraphsForHTML(subgraphs)
|
|
layout := computeLayout(merged)
|
|
renderGraphHTML(layout, merged)
|
|
return nil
|
|
}
|
|
|
|
if graphOpen {
|
|
for i, subgraph := range subgraphs {
|
|
layout := computeLayout(subgraph)
|
|
renderGraphCompact(layout, subgraph)
|
|
if i < len(subgraphs)-1 {
|
|
fmt.Println(strings.Repeat("─", 60))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
for i, subgraph := range subgraphs {
|
|
layout := computeLayout(subgraph)
|
|
if graphDOT {
|
|
renderGraphDOT(layout, subgraph)
|
|
} else if graphCompact {
|
|
renderGraphCompact(layout, subgraph)
|
|
} else if graphBox {
|
|
renderGraph(layout, subgraph)
|
|
} else {
|
|
renderGraphVisual(layout, subgraph)
|
|
}
|
|
if !graphDOT && i < len(subgraphs)-1 {
|
|
fmt.Println(strings.Repeat("─", 60))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func renderGraphSingleSubgraph(subgraph *TemplateSubgraph) error {
|
|
if graphOpen {
|
|
subgraph = filterSubgraphOpen(subgraph)
|
|
if subgraph == nil || len(subgraph.Issues) == 0 {
|
|
fmt.Println("No open issues in subgraph")
|
|
return nil
|
|
}
|
|
}
|
|
|
|
layout := computeLayout(subgraph)
|
|
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"root": subgraph.Root,
|
|
"issues": subgraph.Issues,
|
|
"layout": layout,
|
|
})
|
|
}
|
|
|
|
if graphOpen {
|
|
renderGraphCompact(layout, subgraph)
|
|
return nil
|
|
}
|
|
|
|
if graphDOT {
|
|
renderGraphDOT(layout, subgraph)
|
|
} else if graphHTML {
|
|
renderGraphHTML(layout, subgraph)
|
|
} else if graphCompact {
|
|
renderGraphCompact(layout, subgraph)
|
|
} else if graphBox {
|
|
renderGraph(layout, subgraph)
|
|
} else {
|
|
renderGraphVisual(layout, subgraph)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var graphCheckCmd = &cobra.Command{
|
|
Use: "check",
|
|
Short: "Check dependency graph integrity",
|
|
Long: `Check the dependency graph for cycles, orphans, and other integrity issues.
|
|
|
|
Returns exit code 0 if the graph is clean, 1 if issues are found.`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("graph-check")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if usesProxiedServer() {
|
|
return runGraphCheckProxiedServer(rootCtx)
|
|
}
|
|
|
|
cycles, err := store.DetectCycles(rootCtx)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("cycle detection failed: %v", err)
|
|
}
|
|
return renderGraphCheck(cycles)
|
|
},
|
|
}
|
|
|
|
func renderGraphCheck(cycles [][]*types.Issue) error {
|
|
type GraphCheckResult struct {
|
|
Clean bool `json:"clean"`
|
|
Cycles [][]string `json:"cycles"`
|
|
Summary struct {
|
|
CycleCount int `json:"cycle_count"`
|
|
} `json:"summary"`
|
|
}
|
|
|
|
result := GraphCheckResult{Clean: true}
|
|
|
|
for _, cycle := range cycles {
|
|
ids := make([]string, len(cycle))
|
|
for i, issue := range cycle {
|
|
ids[i] = issue.ID
|
|
}
|
|
result.Cycles = append(result.Cycles, ids)
|
|
}
|
|
result.Summary.CycleCount = len(cycles)
|
|
|
|
if len(cycles) > 0 {
|
|
result.Clean = false
|
|
}
|
|
|
|
if jsonOutput {
|
|
if err := outputJSON(result); err != nil {
|
|
return err
|
|
}
|
|
if !result.Clean {
|
|
return SilentExit()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
if result.Clean {
|
|
fmt.Printf("\n%s Graph integrity check passed\n\n", ui.RenderPass("✓"))
|
|
} else {
|
|
fmt.Printf("\n%s Graph integrity issues found\n\n", ui.RenderFail("✗"))
|
|
}
|
|
|
|
if len(result.Cycles) > 0 {
|
|
fmt.Printf("%s Cycles (%d):\n\n", ui.RenderFail("⚠"), len(result.Cycles))
|
|
for _, cycle := range result.Cycles {
|
|
fmt.Printf(" %s → %s\n", strings.Join(cycle, " → "), cycle[0])
|
|
}
|
|
fmt.Println()
|
|
} else {
|
|
fmt.Printf(" %s No dependency cycles\n", ui.RenderPass("✓"))
|
|
}
|
|
|
|
fmt.Println()
|
|
|
|
if !result.Clean {
|
|
return SilentExit()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func init() {
|
|
graphCmd.Flags().BoolVar(&graphAll, "all", false, "Show graph for all open issues")
|
|
graphCmd.Flags().BoolVar(&graphCompact, "compact", false, "Tree format, one line per issue, more scannable")
|
|
graphCmd.Flags().BoolVar(&graphBox, "box", false, "ASCII boxes showing layers")
|
|
graphCmd.Flags().BoolVar(&graphDOT, "dot", false, "Output Graphviz DOT format (pipe to: dot -Tsvg > graph.svg)")
|
|
graphCmd.Flags().BoolVar(&graphHTML, "html", false, "Output self-contained interactive HTML (redirect to file)")
|
|
graphCmd.Flags().BoolVar(&graphOpen, "open", false, "Show only open issues (filters out closed/deferred), forces compact layer format")
|
|
// Defensive row cap (be-x42v): exits 2 on overage, default disabled.
|
|
addMaxRowsFlag(graphCmd)
|
|
graphCmd.ValidArgsFunction = issueIDCompletion
|
|
rootCmd.AddCommand(graphCmd)
|
|
graphCmd.AddCommand(graphCheckCmd)
|
|
}
|
|
|
|
// loadGraphSubgraph loads an issue and its subgraph for visualization
|
|
// Unlike template loading, this includes ALL dependency types (not just parent-child)
|
|
func loadGraphSubgraph(ctx context.Context, s storage.DoltStorage, issueID string) (*TemplateSubgraph, error) {
|
|
if s == nil {
|
|
return nil, fmt.Errorf("no database connection")
|
|
}
|
|
|
|
// Get the root issue
|
|
root, err := s.GetIssue(ctx, issueID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get issue: %w", err)
|
|
}
|
|
if root == nil {
|
|
return nil, fmt.Errorf("issue %s not found", issueID)
|
|
}
|
|
|
|
subgraph := &TemplateSubgraph{
|
|
Root: root,
|
|
Issues: []*types.Issue{root},
|
|
IssueMap: map[string]*types.Issue{root.ID: root},
|
|
}
|
|
|
|
// BFS to find all connected issues (via any dependency type).
|
|
// Traverse both directions: dependents AND dependencies (GH#2145).
|
|
queue := []string{root.ID}
|
|
visited := map[string]bool{root.ID: true}
|
|
|
|
for len(queue) > 0 {
|
|
currentID := queue[0]
|
|
queue = queue[1:]
|
|
|
|
// Get issues that depend on this one (dependents)
|
|
dependents, err := s.GetDependents(ctx, currentID)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, dep := range dependents {
|
|
if !visited[dep.ID] {
|
|
visited[dep.ID] = true
|
|
subgraph.Issues = append(subgraph.Issues, dep)
|
|
subgraph.IssueMap[dep.ID] = dep
|
|
queue = append(queue, dep.ID)
|
|
}
|
|
}
|
|
|
|
// Get issues this one depends on (dependencies)
|
|
dependencies, err := s.GetDependencies(ctx, currentID)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, dep := range dependencies {
|
|
if !visited[dep.ID] {
|
|
visited[dep.ID] = true
|
|
subgraph.Issues = append(subgraph.Issues, dep)
|
|
subgraph.IssueMap[dep.ID] = dep
|
|
queue = append(queue, dep.ID)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Load all dependencies within the subgraph
|
|
for _, issue := range subgraph.Issues {
|
|
deps, err := s.GetDependencyRecords(ctx, issue.ID)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, dep := range deps {
|
|
// Resolve external deps via routing (bd-k0pfm)
|
|
if strings.HasPrefix(dep.DependsOnID, "external:") {
|
|
parts := strings.SplitN(dep.DependsOnID, ":", 3)
|
|
if len(parts) == 3 && parts[2] != "" {
|
|
targetID := parts[2]
|
|
if _, exists := subgraph.IssueMap[targetID]; !exists {
|
|
result, routeErr := resolveAndGetIssueWithRouting(ctx, store, targetID)
|
|
if routeErr == nil && result != nil && result.Issue != nil {
|
|
subgraph.Issues = append(subgraph.Issues, result.Issue)
|
|
subgraph.IssueMap[result.Issue.ID] = result.Issue
|
|
// Rewrite dep to use the resolved issue ID
|
|
dep.DependsOnID = result.Issue.ID
|
|
result.Close()
|
|
} else {
|
|
if result != nil {
|
|
result.Close()
|
|
}
|
|
continue
|
|
}
|
|
} else {
|
|
dep.DependsOnID = targetID
|
|
}
|
|
}
|
|
}
|
|
// Only include dependencies where both ends are in the subgraph
|
|
if _, ok := subgraph.IssueMap[dep.DependsOnID]; ok {
|
|
subgraph.Dependencies = append(subgraph.Dependencies, dep)
|
|
}
|
|
}
|
|
}
|
|
|
|
return subgraph, nil
|
|
}
|
|
|
|
// loadAllGraphSubgraphs loads all open issues and groups them by connected component
|
|
// Each component is a subgraph of issues that share dependencies. The defensive
|
|
// row cap (be-x42v) is propagated to each per-status SearchIssues call so any
|
|
// single status that exceeds the cap returns the typed error directly.
|
|
func loadAllGraphSubgraphs(ctx context.Context, s storage.DoltStorage, maxRows int, maxRowsSource string) ([]*TemplateSubgraph, error) {
|
|
if s == nil {
|
|
return nil, fmt.Errorf("no database connection")
|
|
}
|
|
|
|
// Get all open issues (open, in_progress, blocked)
|
|
// We need to make multiple calls since IssueFilter takes a single status
|
|
var allIssues []*types.Issue
|
|
for _, status := range []types.Status{types.StatusOpen, types.StatusInProgress, types.StatusBlocked} {
|
|
statusCopy := status
|
|
issues, err := s.SearchIssues(ctx, "", types.IssueFilter{
|
|
Status: &statusCopy,
|
|
MaxRows: maxRows,
|
|
MaxRowsSource: maxRowsSource,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to search issues: %w", err)
|
|
}
|
|
allIssues = append(allIssues, issues...)
|
|
}
|
|
|
|
if len(allIssues) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
// Build issue map
|
|
issueMap := make(map[string]*types.Issue)
|
|
for _, issue := range allIssues {
|
|
issueMap[issue.ID] = issue
|
|
}
|
|
|
|
// Load all dependencies between these issues
|
|
allDeps := make([]*types.Dependency, 0)
|
|
for _, issue := range allIssues {
|
|
deps, err := s.GetDependencyRecords(ctx, issue.ID)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, dep := range deps {
|
|
// Resolve external deps via routing (bd-k0pfm)
|
|
if strings.HasPrefix(dep.DependsOnID, "external:") {
|
|
parts := strings.SplitN(dep.DependsOnID, ":", 3)
|
|
if len(parts) == 3 && parts[2] != "" {
|
|
targetID := parts[2]
|
|
if _, exists := issueMap[targetID]; !exists {
|
|
result, routeErr := resolveAndGetIssueWithRouting(ctx, store, targetID)
|
|
if routeErr == nil && result != nil && result.Issue != nil {
|
|
allIssues = append(allIssues, result.Issue)
|
|
issueMap[result.Issue.ID] = result.Issue
|
|
dep.DependsOnID = result.Issue.ID
|
|
result.Close()
|
|
} else {
|
|
if result != nil {
|
|
result.Close()
|
|
}
|
|
continue
|
|
}
|
|
} else {
|
|
dep.DependsOnID = targetID
|
|
}
|
|
}
|
|
}
|
|
// Only include deps where both ends are in our issue set
|
|
if _, ok := issueMap[dep.DependsOnID]; ok {
|
|
allDeps = append(allDeps, dep)
|
|
}
|
|
}
|
|
}
|
|
|
|
return assembleAllSubgraphs(allIssues, issueMap, allDeps), nil
|
|
}
|
|
|
|
func assembleAllSubgraphs(allIssues []*types.Issue, issueMap map[string]*types.Issue, allDeps []*types.Dependency) []*TemplateSubgraph {
|
|
// Build adjacency list for union-find
|
|
adj := make(map[string][]string)
|
|
for _, dep := range allDeps {
|
|
adj[dep.IssueID] = append(adj[dep.IssueID], dep.DependsOnID)
|
|
adj[dep.DependsOnID] = append(adj[dep.DependsOnID], dep.IssueID)
|
|
}
|
|
|
|
// Find connected components using BFS
|
|
visited := make(map[string]bool)
|
|
var components [][]string
|
|
|
|
for _, issue := range allIssues {
|
|
if visited[issue.ID] {
|
|
continue
|
|
}
|
|
|
|
// BFS to find all connected issues
|
|
var component []string
|
|
queue := []string{issue.ID}
|
|
visited[issue.ID] = true
|
|
|
|
for len(queue) > 0 {
|
|
current := queue[0]
|
|
queue = queue[1:]
|
|
component = append(component, current)
|
|
|
|
for _, neighbor := range adj[current] {
|
|
if !visited[neighbor] {
|
|
visited[neighbor] = true
|
|
queue = append(queue, neighbor)
|
|
}
|
|
}
|
|
}
|
|
|
|
components = append(components, component)
|
|
}
|
|
|
|
// Sort components by size (largest first) and then by priority of first issue
|
|
sort.Slice(components, func(i, j int) bool {
|
|
// First by size (descending)
|
|
if len(components[i]) != len(components[j]) {
|
|
return len(components[i]) > len(components[j])
|
|
}
|
|
// Then by priority of first issue (ascending = higher priority first)
|
|
issueI := issueMap[components[i][0]]
|
|
issueJ := issueMap[components[j][0]]
|
|
return issueI.Priority < issueJ.Priority
|
|
})
|
|
|
|
// Create subgraph for each component
|
|
var subgraphs []*TemplateSubgraph
|
|
for _, component := range components {
|
|
if len(component) == 0 {
|
|
continue
|
|
}
|
|
|
|
// Find the best "root" for this component
|
|
// Prefer: epics > highest priority > oldest
|
|
var root *types.Issue
|
|
for _, id := range component {
|
|
issue := issueMap[id]
|
|
if root == nil {
|
|
root = issue
|
|
continue
|
|
}
|
|
// Prefer epics
|
|
if issue.IssueType == types.TypeEpic && root.IssueType != types.TypeEpic {
|
|
root = issue
|
|
continue
|
|
}
|
|
if root.IssueType == types.TypeEpic && issue.IssueType != types.TypeEpic {
|
|
continue
|
|
}
|
|
// Prefer higher priority (lower number)
|
|
if issue.Priority < root.Priority {
|
|
root = issue
|
|
}
|
|
}
|
|
|
|
subgraph := &TemplateSubgraph{
|
|
Root: root,
|
|
IssueMap: make(map[string]*types.Issue),
|
|
}
|
|
|
|
for _, id := range component {
|
|
issue := issueMap[id]
|
|
subgraph.Issues = append(subgraph.Issues, issue)
|
|
subgraph.IssueMap[id] = issue
|
|
}
|
|
|
|
// Add dependencies for this component
|
|
for _, dep := range allDeps {
|
|
if _, inComponent := subgraph.IssueMap[dep.IssueID]; inComponent {
|
|
if _, depInComponent := subgraph.IssueMap[dep.DependsOnID]; depInComponent {
|
|
subgraph.Dependencies = append(subgraph.Dependencies, dep)
|
|
}
|
|
}
|
|
}
|
|
|
|
subgraphs = append(subgraphs, subgraph)
|
|
}
|
|
|
|
return subgraphs
|
|
}
|
|
|
|
// isOpenStatus returns true for statuses considered "open" / actionable.
|
|
// Closed and deferred (frozen) issues are excluded by --open.
|
|
func isOpenStatus(s types.Status) bool {
|
|
switch s {
|
|
case types.StatusOpen, types.StatusInProgress, types.StatusBlocked:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// filterSubgraphOpen removes closed/deferred issues from a subgraph and
|
|
// computes a transitive closure of blocking edges through removed nodes so
|
|
// that indirect blocking relationships are preserved.
|
|
//
|
|
// Example: if A(open) blocks B(closed) blocks C(open), the filtered graph
|
|
// contains A and C with a synthetic edge A→C.
|
|
func filterSubgraphOpen(subgraph *TemplateSubgraph) *TemplateSubgraph {
|
|
if subgraph == nil {
|
|
return nil
|
|
}
|
|
|
|
openSet := make(map[string]bool)
|
|
for _, issue := range subgraph.Issues {
|
|
if isOpenStatus(issue.Status) {
|
|
openSet[issue.ID] = true
|
|
}
|
|
}
|
|
|
|
if len(openSet) == 0 {
|
|
return nil
|
|
}
|
|
|
|
// Build full blocking graph (all nodes, including closed) for transitive
|
|
// closure. blocksAdj: A→B means "A blocks B" (B depends on A).
|
|
blocksAdj := make(map[string][]string)
|
|
for _, dep := range subgraph.Dependencies {
|
|
if dep.Type == types.DepBlocks {
|
|
blocksAdj[dep.DependsOnID] = append(blocksAdj[dep.DependsOnID], dep.IssueID)
|
|
}
|
|
}
|
|
|
|
// For each open node, BFS forward through the blocking graph to find all
|
|
// reachable open nodes. Each such reachable open node has a transitive
|
|
// blocking relationship.
|
|
type edge struct{ from, to string }
|
|
syntheticEdges := make(map[edge]bool)
|
|
|
|
for src := range openSet {
|
|
visited := map[string]bool{src: true}
|
|
queue := []string{src}
|
|
for len(queue) > 0 {
|
|
cur := queue[0]
|
|
queue = queue[1:]
|
|
for _, next := range blocksAdj[cur] {
|
|
if visited[next] {
|
|
continue
|
|
}
|
|
visited[next] = true
|
|
if openSet[next] {
|
|
syntheticEdges[edge{src, next}] = true
|
|
}
|
|
if !openSet[next] {
|
|
queue = append(queue, next)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Build filtered subgraph
|
|
filtered := &TemplateSubgraph{
|
|
IssueMap: make(map[string]*types.Issue, len(openSet)),
|
|
}
|
|
for _, issue := range subgraph.Issues {
|
|
if openSet[issue.ID] {
|
|
filtered.Issues = append(filtered.Issues, issue)
|
|
filtered.IssueMap[issue.ID] = issue
|
|
}
|
|
}
|
|
|
|
// Keep non-blocks deps where both ends are open, and rebuild blocks
|
|
// deps from the transitive closure.
|
|
seen := make(map[edge]bool)
|
|
for _, dep := range subgraph.Dependencies {
|
|
if !openSet[dep.IssueID] || !openSet[dep.DependsOnID] {
|
|
continue
|
|
}
|
|
if dep.Type == types.DepBlocks {
|
|
e := edge{dep.DependsOnID, dep.IssueID}
|
|
if !seen[e] {
|
|
seen[e] = true
|
|
filtered.Dependencies = append(filtered.Dependencies, dep)
|
|
}
|
|
} else {
|
|
filtered.Dependencies = append(filtered.Dependencies, dep)
|
|
}
|
|
}
|
|
// Add synthetic transitive edges
|
|
for e := range syntheticEdges {
|
|
if seen[e] {
|
|
continue
|
|
}
|
|
seen[e] = true
|
|
filtered.Dependencies = append(filtered.Dependencies, &types.Dependency{
|
|
IssueID: e.to,
|
|
DependsOnID: e.from,
|
|
Type: types.DepBlocks,
|
|
})
|
|
}
|
|
|
|
// Pick root: prefer original root if still open, else highest-priority open issue
|
|
if subgraph.Root != nil && openSet[subgraph.Root.ID] {
|
|
filtered.Root = subgraph.Root
|
|
} else {
|
|
for _, issue := range filtered.Issues {
|
|
if filtered.Root == nil || issue.Priority < filtered.Root.Priority {
|
|
filtered.Root = issue
|
|
}
|
|
}
|
|
}
|
|
|
|
return filtered
|
|
}
|
|
|
|
// computeLayout assigns layers to nodes using topological sort
|
|
// mergeSubgraphsForHTML joins disconnected components into one subgraph so
|
|
// `bd graph --all --html` emits a single valid HTML document.
|
|
func mergeSubgraphsForHTML(subgraphs []*TemplateSubgraph) *TemplateSubgraph {
|
|
switch len(subgraphs) {
|
|
case 0:
|
|
return &TemplateSubgraph{IssueMap: make(map[string]*types.Issue)}
|
|
case 1:
|
|
return subgraphs[0]
|
|
}
|
|
merged := &TemplateSubgraph{
|
|
IssueMap: make(map[string]*types.Issue),
|
|
}
|
|
for _, sg := range subgraphs {
|
|
for _, issue := range sg.Issues {
|
|
merged.IssueMap[issue.ID] = issue
|
|
}
|
|
merged.Dependencies = append(merged.Dependencies, sg.Dependencies...)
|
|
}
|
|
merged.Issues = make([]*types.Issue, 0, len(merged.IssueMap))
|
|
for _, issue := range merged.IssueMap {
|
|
merged.Issues = append(merged.Issues, issue)
|
|
}
|
|
sort.Slice(merged.Issues, func(i, j int) bool {
|
|
return merged.Issues[i].ID < merged.Issues[j].ID
|
|
})
|
|
return merged
|
|
}
|
|
|
|
func computeLayout(subgraph *TemplateSubgraph) *GraphLayout {
|
|
layout := &GraphLayout{
|
|
Nodes: make(map[string]*GraphNode),
|
|
}
|
|
if subgraph.Root != nil {
|
|
layout.RootID = subgraph.Root.ID
|
|
}
|
|
|
|
// Build dependency map (only "blocks" dependencies, not parent-child)
|
|
dependsOn := make(map[string][]string)
|
|
blockedBy := make(map[string][]string)
|
|
|
|
for _, dep := range subgraph.Dependencies {
|
|
if dep.Type == types.DepBlocks {
|
|
// dep.IssueID depends on dep.DependsOnID
|
|
dependsOn[dep.IssueID] = append(dependsOn[dep.IssueID], dep.DependsOnID)
|
|
blockedBy[dep.DependsOnID] = append(blockedBy[dep.DependsOnID], dep.IssueID)
|
|
}
|
|
}
|
|
|
|
// Initialize nodes
|
|
for _, issue := range subgraph.Issues {
|
|
layout.Nodes[issue.ID] = &GraphNode{
|
|
Issue: issue,
|
|
Layer: -1, // Unassigned
|
|
DependsOn: dependsOn[issue.ID],
|
|
}
|
|
}
|
|
|
|
// Assign layers using longest path from sources
|
|
// Layer 0 = nodes with no dependencies
|
|
changed := true
|
|
for changed {
|
|
changed = false
|
|
for id, node := range layout.Nodes {
|
|
if node.Layer >= 0 {
|
|
continue // Already assigned
|
|
}
|
|
|
|
deps := dependsOn[id]
|
|
if len(deps) == 0 {
|
|
// No dependencies - layer 0
|
|
node.Layer = 0
|
|
changed = true
|
|
} else {
|
|
// Check if all dependencies have layers assigned
|
|
maxDepLayer := -1
|
|
allAssigned := true
|
|
for _, depID := range deps {
|
|
depNode := layout.Nodes[depID]
|
|
if depNode == nil || depNode.Layer < 0 {
|
|
allAssigned = false
|
|
break
|
|
}
|
|
if depNode.Layer > maxDepLayer {
|
|
maxDepLayer = depNode.Layer
|
|
}
|
|
}
|
|
if allAssigned {
|
|
node.Layer = maxDepLayer + 1
|
|
changed = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Handle any unassigned nodes (cycles or disconnected)
|
|
for _, node := range layout.Nodes {
|
|
if node.Layer < 0 {
|
|
node.Layer = 0
|
|
}
|
|
}
|
|
|
|
// Lift children to at least their parent's layer (GH#1748).
|
|
// Parent-child deps are not blocking deps, but children logically belong
|
|
// to their parent's scope. If a parent epic is blocked (higher layer),
|
|
// its children should appear in the same layer, not float in Layer 0.
|
|
parentOf := make(map[string]string) // childID -> parentID
|
|
for _, dep := range subgraph.Dependencies {
|
|
if dep.Type == types.DepParentChild {
|
|
parentOf[dep.IssueID] = dep.DependsOnID
|
|
}
|
|
}
|
|
if len(parentOf) > 0 {
|
|
// Iterate until stable — handles nested parent-child hierarchies
|
|
changed = true
|
|
for changed {
|
|
changed = false
|
|
for childID, parentID := range parentOf {
|
|
childNode := layout.Nodes[childID]
|
|
parentNode := layout.Nodes[parentID]
|
|
if childNode != nil && parentNode != nil && childNode.Layer < parentNode.Layer {
|
|
childNode.Layer = parentNode.Layer
|
|
changed = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Build layers array
|
|
for _, node := range layout.Nodes {
|
|
if node.Layer > layout.MaxLayer {
|
|
layout.MaxLayer = node.Layer
|
|
}
|
|
}
|
|
|
|
layout.Layers = make([][]string, layout.MaxLayer+1)
|
|
for id, node := range layout.Nodes {
|
|
layout.Layers[node.Layer] = append(layout.Layers[node.Layer], id)
|
|
}
|
|
|
|
// Sort nodes within each layer for consistent ordering
|
|
for i := range layout.Layers {
|
|
sort.Strings(layout.Layers[i])
|
|
}
|
|
|
|
// Assign vertical positions within layers
|
|
for _, layer := range layout.Layers {
|
|
for pos, id := range layer {
|
|
layout.Nodes[id].Position = pos
|
|
}
|
|
}
|
|
|
|
return layout
|
|
}
|
|
|
|
// renderGraph renders the ASCII visualization
|
|
func renderGraph(layout *GraphLayout, subgraph *TemplateSubgraph) {
|
|
if len(layout.Nodes) == 0 {
|
|
fmt.Println("Empty graph")
|
|
return
|
|
}
|
|
|
|
fmt.Printf("\n%s Dependency graph for %s:\n\n", ui.RenderAccent("📊"), layout.RootID)
|
|
|
|
// Calculate box width based on longest title
|
|
maxTitleLen := 0
|
|
for _, node := range layout.Nodes {
|
|
titleLen := len(truncateTitle(node.Issue.Title, 30))
|
|
if titleLen > maxTitleLen {
|
|
maxTitleLen = titleLen
|
|
}
|
|
}
|
|
boxWidth := maxTitleLen + 4 // padding
|
|
|
|
// Render each layer
|
|
// For simplicity, we'll render layer by layer with arrows between them
|
|
|
|
// First, show the legend
|
|
fmt.Println(" Status: ○ open ◐ in_progress ● blocked ✓ closed")
|
|
fmt.Println()
|
|
|
|
// Build dependency counts from subgraph
|
|
blocksCounts, blockedByCounts := computeDependencyCounts(subgraph)
|
|
|
|
// Render layers left to right
|
|
layerBoxes := make([][]string, len(layout.Layers))
|
|
|
|
for layerIdx, layer := range layout.Layers {
|
|
var boxes []string
|
|
for _, id := range layer {
|
|
node := layout.Nodes[id]
|
|
box := renderNodeBoxWithDeps(node, boxWidth, blocksCounts[id], blockedByCounts[id])
|
|
boxes = append(boxes, box)
|
|
}
|
|
layerBoxes[layerIdx] = boxes
|
|
}
|
|
|
|
// Find max height per layer
|
|
maxHeight := 0
|
|
for _, boxes := range layerBoxes {
|
|
h := len(boxes) * 4 // Each box is ~3 lines + 1 gap
|
|
if h > maxHeight {
|
|
maxHeight = h
|
|
}
|
|
}
|
|
|
|
// Render horizontally (simplified - just show boxes with arrows)
|
|
for layerIdx, boxes := range layerBoxes {
|
|
// Print layer header
|
|
fmt.Printf(" Layer %d", layerIdx)
|
|
if layerIdx == 0 {
|
|
fmt.Print(" (ready)")
|
|
}
|
|
fmt.Println()
|
|
|
|
for _, box := range boxes {
|
|
fmt.Println(box)
|
|
}
|
|
|
|
// Print arrows to next layer if not last
|
|
if layerIdx < len(layerBoxes)-1 {
|
|
fmt.Println(" │")
|
|
fmt.Println(" ▼")
|
|
}
|
|
fmt.Println()
|
|
}
|
|
|
|
// Show dependency summary
|
|
if len(subgraph.Dependencies) > 0 {
|
|
blocksDeps := 0
|
|
for _, dep := range subgraph.Dependencies {
|
|
if dep.Type == types.DepBlocks {
|
|
blocksDeps++
|
|
}
|
|
}
|
|
if blocksDeps > 0 {
|
|
fmt.Printf(" Dependencies: %d blocking relationships\n", blocksDeps)
|
|
}
|
|
}
|
|
|
|
// Show summary
|
|
fmt.Printf(" Total: %d issues across %d layers\n\n", len(layout.Nodes), len(layout.Layers))
|
|
}
|
|
|
|
// renderGraphCompact renders the graph in compact tree format
|
|
// One line per issue, more scannable, uses tree connectors (├──, └──, │)
|
|
func renderGraphCompact(layout *GraphLayout, subgraph *TemplateSubgraph) {
|
|
if len(layout.Nodes) == 0 {
|
|
fmt.Println("Empty graph")
|
|
return
|
|
}
|
|
|
|
fmt.Printf("\n%s Dependency graph for %s (%d issues, %d layers)\n\n",
|
|
ui.RenderAccent("📊"), layout.RootID, len(layout.Nodes), len(layout.Layers))
|
|
|
|
// Legend
|
|
fmt.Println(" Status: ○ open ◐ in_progress ● blocked ✓ closed ❄ deferred")
|
|
fmt.Println()
|
|
|
|
// Build parent-child map from subgraph dependencies
|
|
children := make(map[string][]string) // parent -> children
|
|
childSet := make(map[string]bool) // track which issues are children
|
|
|
|
for _, dep := range subgraph.Dependencies {
|
|
if dep.Type == types.DepParentChild {
|
|
children[dep.DependsOnID] = append(children[dep.DependsOnID], dep.IssueID)
|
|
childSet[dep.IssueID] = true
|
|
}
|
|
}
|
|
|
|
// Sort children by priority then ID for consistent output
|
|
for parentID := range children {
|
|
sort.Slice(children[parentID], func(i, j int) bool {
|
|
nodeI := layout.Nodes[children[parentID][i]]
|
|
nodeJ := layout.Nodes[children[parentID][j]]
|
|
if nodeI.Issue.Priority != nodeJ.Issue.Priority {
|
|
return nodeI.Issue.Priority < nodeJ.Issue.Priority
|
|
}
|
|
return utils.NaturalCompareIDs(nodeI.Issue.ID, nodeJ.Issue.ID) < 0
|
|
})
|
|
}
|
|
|
|
// Render by layer with tree structure
|
|
for layerIdx, layer := range layout.Layers {
|
|
// Layer header
|
|
layerHeader := fmt.Sprintf("LAYER %d", layerIdx)
|
|
if layerIdx == 0 {
|
|
layerHeader += " (ready)"
|
|
}
|
|
fmt.Printf(" %s\n", ui.RenderAccent(layerHeader))
|
|
|
|
for i, id := range layer {
|
|
node := layout.Nodes[id]
|
|
isLast := i == len(layer)-1
|
|
|
|
// Format node line
|
|
line := formatCompactNode(node)
|
|
|
|
// Tree connector
|
|
connector := "├── "
|
|
if isLast {
|
|
connector = "└── "
|
|
}
|
|
|
|
fmt.Printf(" %s%s\n", connector, line)
|
|
|
|
// Render children (if this issue has children in the subgraph)
|
|
if childIDs, ok := children[id]; ok && len(childIDs) > 0 {
|
|
childPrefix := "│ "
|
|
if isLast {
|
|
childPrefix = " "
|
|
}
|
|
renderCompactChildren(layout, childIDs, children, childPrefix, 1)
|
|
}
|
|
}
|
|
fmt.Println()
|
|
}
|
|
}
|
|
|
|
// renderCompactChildren recursively renders children in tree format
|
|
func renderCompactChildren(layout *GraphLayout, childIDs []string, children map[string][]string, prefix string, depth int) {
|
|
for i, childID := range childIDs {
|
|
node := layout.Nodes[childID]
|
|
if node == nil {
|
|
continue
|
|
}
|
|
|
|
isLast := i == len(childIDs)-1
|
|
connector := "├── "
|
|
if isLast {
|
|
connector = "└── "
|
|
}
|
|
|
|
line := formatCompactNode(node)
|
|
fmt.Printf(" %s%s%s\n", prefix, connector, line)
|
|
|
|
// Recurse for nested children
|
|
if grandchildren, ok := children[childID]; ok && len(grandchildren) > 0 {
|
|
childPrefix := prefix
|
|
if isLast {
|
|
childPrefix += " "
|
|
} else {
|
|
childPrefix += "│ "
|
|
}
|
|
renderCompactChildren(layout, grandchildren, children, childPrefix, depth+1)
|
|
}
|
|
}
|
|
}
|
|
|
|
// formatCompactNode formats a single node for compact output
|
|
// Format: STATUS_ICON ID PRIORITY Title
|
|
func formatCompactNode(node *GraphNode) string {
|
|
status := string(node.Issue.Status)
|
|
|
|
// Use shared status icon with semantic color
|
|
statusIcon := ui.RenderStatusIcon(status)
|
|
|
|
// Priority with icon
|
|
priorityTag := ui.RenderPriority(node.Issue.Priority)
|
|
|
|
// Title - truncate if too long
|
|
title := truncateTitle(node.Issue.Title, 50)
|
|
|
|
// Build line - apply status style to entire line for closed issues
|
|
style := ui.GetStatusStyle(status)
|
|
if node.Issue.Status == types.StatusClosed {
|
|
return fmt.Sprintf("%s %s %s %s",
|
|
statusIcon,
|
|
style.Render(node.Issue.ID),
|
|
style.Render(fmt.Sprintf("● P%d", node.Issue.Priority)),
|
|
style.Render(title))
|
|
}
|
|
|
|
return fmt.Sprintf("%s %s %s %s", statusIcon, node.Issue.ID, priorityTag, title)
|
|
}
|
|
|
|
// renderNodeBox renders a single node as an ASCII box
|
|
// Uses semantic status styles from ui package for consistency
|
|
func renderNodeBox(node *GraphNode, width int) string {
|
|
title := truncateTitle(node.Issue.Title, width-4)
|
|
paddedTitle := padRight(title, width-4)
|
|
status := string(node.Issue.Status)
|
|
|
|
// Use shared status icon and style
|
|
statusIcon := ui.RenderStatusIcon(status)
|
|
style := ui.GetStatusStyle(status)
|
|
|
|
// Apply style to title for actionable statuses
|
|
var titleStr string
|
|
if node.Issue.Status == types.StatusOpen {
|
|
titleStr = paddedTitle // no color for open - available but not urgent
|
|
} else {
|
|
titleStr = style.Render(paddedTitle)
|
|
}
|
|
|
|
id := node.Issue.ID
|
|
|
|
// Build the box
|
|
topBottom := " ┌" + strings.Repeat("─", width) + "┐"
|
|
middle := fmt.Sprintf(" │ %s %s │", statusIcon, titleStr)
|
|
idLine := fmt.Sprintf(" │ %s │", ui.RenderMuted(padRight(id, width-2)))
|
|
bottom := " └" + strings.Repeat("─", width) + "┘"
|
|
|
|
return topBottom + "\n" + middle + "\n" + idLine + "\n" + bottom
|
|
}
|
|
|
|
// truncateTitle truncates a title to max length (rune-safe)
|
|
func truncateTitle(title string, maxLen int) string {
|
|
runes := []rune(title)
|
|
if len(runes) <= maxLen {
|
|
return title
|
|
}
|
|
return string(runes[:maxLen-1]) + "…"
|
|
}
|
|
|
|
// padRight pads a string to the right with spaces (rune-safe)
|
|
func padRight(s string, width int) string {
|
|
runes := []rune(s)
|
|
if len(runes) >= width {
|
|
return string(runes[:width])
|
|
}
|
|
return s + strings.Repeat(" ", width-len(runes))
|
|
}
|
|
|
|
// computeDependencyCounts calculates how many issues each issue blocks and is blocked by
|
|
// Excludes parent-child relationships and the root issue from counts to reduce cognitive noise
|
|
func computeDependencyCounts(subgraph *TemplateSubgraph) (blocks map[string]int, blockedBy map[string]int) {
|
|
blocks = make(map[string]int)
|
|
blockedBy = make(map[string]int)
|
|
|
|
if subgraph == nil {
|
|
return blocks, blockedBy
|
|
}
|
|
|
|
rootID := ""
|
|
if subgraph.Root != nil {
|
|
rootID = subgraph.Root.ID
|
|
}
|
|
|
|
for _, dep := range subgraph.Dependencies {
|
|
// Only count "blocks" dependencies (not parent-child, related, etc.)
|
|
if dep.Type != types.DepBlocks {
|
|
continue
|
|
}
|
|
|
|
// Skip if the blocker is the root issue - this is obvious from graph structure
|
|
// and showing "needs:1" when it's just the parent epic is cognitive noise
|
|
if dep.DependsOnID == rootID {
|
|
continue
|
|
}
|
|
|
|
// dep.DependsOnID blocks dep.IssueID
|
|
// So dep.DependsOnID "blocks" count increases
|
|
blocks[dep.DependsOnID]++
|
|
// And dep.IssueID "blocked by" count increases
|
|
blockedBy[dep.IssueID]++
|
|
}
|
|
|
|
return blocks, blockedBy
|
|
}
|
|
|
|
// renderNodeBoxWithDeps renders a node box with dependency information
|
|
// Uses semantic status styles from ui package for consistency across commands
|
|
// Design principle: only actionable states get color, closed items fade
|
|
func renderNodeBoxWithDeps(node *GraphNode, width int, blocksCount int, blockedByCount int) string {
|
|
title := truncateTitle(node.Issue.Title, width-4)
|
|
paddedTitle := padRight(title, width-4)
|
|
status := string(node.Issue.Status)
|
|
|
|
// Use shared status icon and style from ui package
|
|
statusIcon := ui.RenderStatusIcon(status)
|
|
style := ui.GetStatusStyle(status)
|
|
|
|
// Apply style to title for actionable statuses
|
|
var titleStr string
|
|
if node.Issue.Status == types.StatusOpen {
|
|
titleStr = paddedTitle // no color for open - available but not urgent
|
|
} else {
|
|
titleStr = style.Render(paddedTitle)
|
|
}
|
|
|
|
id := node.Issue.ID
|
|
|
|
// Build dependency info string - only show if meaningful counts exist
|
|
// Note: we build the plain text version first for padding, then apply colors
|
|
var depInfoPlain string
|
|
var depInfoStyled string
|
|
if blocksCount > 0 || blockedByCount > 0 {
|
|
plainParts := []string{}
|
|
styledParts := []string{}
|
|
if blocksCount > 0 {
|
|
plainText := fmt.Sprintf("blocks:%d", blocksCount)
|
|
plainParts = append(plainParts, plainText)
|
|
// Use semantic color for blocks indicator - attention-grabbing
|
|
styledParts = append(styledParts, ui.StatusBlockedStyle.Render(plainText))
|
|
}
|
|
if blockedByCount > 0 {
|
|
plainText := fmt.Sprintf("needs:%d", blockedByCount)
|
|
plainParts = append(plainParts, plainText)
|
|
// Use muted color for needs indicator - informational
|
|
styledParts = append(styledParts, ui.MutedStyle.Render(plainText))
|
|
}
|
|
depInfoPlain = strings.Join(plainParts, " ")
|
|
depInfoStyled = strings.Join(styledParts, " ")
|
|
}
|
|
|
|
// Build the box
|
|
topBottom := " ┌" + strings.Repeat("─", width) + "┐"
|
|
middle := fmt.Sprintf(" │ %s %s │", statusIcon, titleStr)
|
|
idLine := fmt.Sprintf(" │ %s │", ui.RenderMuted(padRight(id, width-2)))
|
|
|
|
var result string
|
|
if depInfoPlain != "" {
|
|
// Pad based on plain text length, then render with styled version
|
|
padding := width - 2 - len([]rune(depInfoPlain))
|
|
if padding < 0 {
|
|
padding = 0
|
|
}
|
|
depLine := fmt.Sprintf(" │ %s%s │", depInfoStyled, strings.Repeat(" ", padding))
|
|
bottom := " └" + strings.Repeat("─", width) + "┘"
|
|
result = topBottom + "\n" + middle + "\n" + idLine + "\n" + depLine + "\n" + bottom
|
|
} else {
|
|
bottom := " └" + strings.Repeat("─", width) + "┘"
|
|
result = topBottom + "\n" + middle + "\n" + idLine + "\n" + bottom
|
|
}
|
|
|
|
return result
|
|
}
|