-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbud.py
More file actions
2048 lines (1819 loc) · 78.9 KB
/
Copy pathbud.py
File metadata and controls
2048 lines (1819 loc) · 78.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2025-2026 Arun Rajkumar
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BUD CRUD endpoints and sub-router aggregation."""
import uuid
from pathlib import Path
from typing import Any, Literal
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, Response, UploadFile, status
from fastapi.responses import PlainTextResponse
from sqlalchemy.ext.asyncio import AsyncSession
from app.agents.skill_mapping import resolve_skill_for_agent
from app.api.v1.bud_chat import router as chat_router
from app.api.v1.bud_designs import router as designs_router
from app.api.v1.bud_estimates import router as estimates_router
from app.api.v1.bud_linked_features import router as linked_features_router
from app.api.v1.bud_prs import router as prs_router
from app.api.v1.bud_qa import router as qa_router
from app.api.v1.bud_todos import router as todos_router
from app.api.v1.bud_versions import router as versions_router
from app.api.v1.bud_workflows import router as workflows_router
from app.core.deps import get_current_user, get_db, get_user_permissions, require_permissions
from app.database import AsyncSessionLocal
from app.models.bud import (
BUDDesignStatus,
BUDDocument,
BUDStatus,
BUDTimelineEvent,
BUDTimelineEventType,
)
from app.models.bud_agent_task import AgentTaskStatus, BUDAgentTask
from app.models.bud_feature_link import BUDFeatureLinkSource
from app.models.bud_version import BUDEditSource
from app.models.user import User
from app.repositories import bud_version as bud_version_repo
from app.repositories.agent_activity import AgentActivityLogRepository
from app.repositories.agent_skill import AgentSkillRepository
from app.repositories.bud import BUDDesignRepository, BUDRepository
from app.repositories.bud_agent_task import BUDAgentTaskRepository
from app.repositories.bud_section_session import BUDSectionSessionRepository
from app.repositories.bud_timeline import BUDTimelineRepository
from app.repositories.bug import BugRepository
from app.repositories.feature_learning import FeatureLearningRepository
from app.schemas.bud import (
BUDAgentTaskRead,
BUDCreate,
BUDLearningRead,
BUDListItem,
BUDRead,
BUDUpdate,
TimelineEventRead,
)
from app.schemas.bud_code_review import (
CodeReviewOverrideRequest,
CodeReviewRepoStatus,
CodeReviewRerunRequest,
CodeReviewStatusResponse,
)
from app.schemas.bud_constants import BUD_AGENT_SECTIONS, EXPORTABLE_SECTIONS
from app.schemas.bud_design import BUDDesignRead
from app.schemas.dev_activity import (
CommitRepoRead,
ContributorRead,
DevActivityRead,
DevActivityResponse,
DevCommitRead,
DevStatsRead,
UntrackedRepoRead,
)
from app.schemas.jobs import BUDAgentTaskPayload
from app.services.agent_activity_logger import PHASE_WORKER_SLUGS, log_agent_activity
from app.services.agent_result_handlers import persist_linked_features_from_markdown
from app.services.agent_task_cancel import (
AgentTaskCancelError,
cancel_task,
is_task_terminal,
)
from app.services.bud_agent_trigger import (
create_agent_task_for_stage,
should_auto_generate_phase,
)
from app.services.bud_assignment_actions import assign_bud, unassign_bud
from app.services.bud_edit_policy import assert_section_editable
from app.services.bud_estimation import estimate_bud_dates
from app.services.bud_timeline import record_event
from app.services.job_queue import JOB_BUD_AGENT, create_job
logger = structlog.get_logger(__name__)
async def _persist_stage_skill_overrides(
db: AsyncSession,
org_id: uuid.UUID,
bud_id: uuid.UUID,
overrides: dict[BUDStatus, uuid.UUID],
) -> None:
"""Validate then store per-stage skill picks for one BUD.
Each ``skill_id`` must (a) belong to the caller's org and (b) have
the correct ``agent_type`` for the stage it's being assigned to —
e.g. picking a ``design`` skill for the ``testing`` stage is
rejected with 400.
"""
from app.agents.skill_mapping import BUD_STAGE_AGENT_TYPE
from app.repositories.agent_skill import AgentSkillRepository
from app.repositories.bud_stage_skill_override import (
BUDStageSkillOverrideRepository,
)
skill_repo = AgentSkillRepository(db, org_id=org_id)
for stage, skill_id in overrides.items():
expected_agent_type = BUD_STAGE_AGENT_TYPE.get(stage)
if expected_agent_type is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Stage '{stage.value}' is not configurable",
)
skill = await skill_repo.get_by_id(skill_id)
if skill is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Skill {skill_id} not found for stage {stage.value}",
)
if skill.agent_type != expected_agent_type:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
f"Skill {skill.skill_slug!r} (agent_type={skill.agent_type.value}) "
f"cannot be assigned to stage {stage.value}; that stage runs the "
f"{expected_agent_type.value} agent."
),
)
override_repo = BUDStageSkillOverrideRepository(db, org_id=org_id)
await override_repo.bulk_set_for_bud(bud_id, overrides)
async def _bud_response(
bud: BUDDocument,
org_id: uuid.UUID,
db: AsyncSession,
) -> BUDRead:
"""Build BUDRead with active (or last-failed) agent task attached."""
task_repo = BUDAgentTaskRepository(db, org_id=org_id)
active_task = await task_repo.get_active_for_bud(bud.id)
if not active_task:
# Only show last-failed if no completed task exists after it (i.e. retry succeeded)
failed = await task_repo.get_latest_failed(bud.id)
if failed:
completed = await task_repo.get_latest_completed(bud.id)
if not completed or completed.created_at < failed.created_at:
active_task = failed
# `updated_at` has an ``onupdate=func.now()`` server default that
# SQLAlchemy doesn't include in INSERT…RETURNING, so on a freshly
# inserted BUD the attribute is "not loaded". Pydantic's sync
# validator would then trigger a lazy SELECT — which can't spawn a
# greenlet from sync context and raises MissingGreenlet. An explicit
# refresh inside the async context eager-loads every column before
# validation, and also picks up anything later phases (auto-assign,
# agent-task creation) mutated on the same row.
await db.refresh(bud)
bud_data = BUDRead.model_validate(bud)
if active_task:
bud_data.active_agent_task = BUDAgentTaskRead.model_validate(active_task)
# ``BUDDesignRead`` declares ``repo_name`` but the ORM model has no
# column or relationship for it — ``from_attributes`` would leave
# it None. Refetch designs via the JOIN-backed list so the per-repo
# banners and chat-panel dropdown can render the actual repo name
# instead of falling back to "default". Skip the extra query when
# the BUD has no design rows (every non-design phase, plus design
# phase before the user clicks "Add").
if bud.designs:
design_repo = BUDDesignRepository(db, org_id=org_id)
design_rows = await design_repo.list_with_repo_names(bud.id)
bud_data.designs = [BUDDesignRead.model_validate(row) for row in design_rows]
# Re-attach the phase-progress banner for synthetic workers (assignment
# / todo-gen / estimation) that don't have BUDAgentTask rows. Without
# this the banner only catches events that fire AFTER mount, so the
# whole chain is invisible if the user navigates away and back.
# Uses the single source of truth ``PHASE_WORKER_SLUGS`` from
# agent_activity_logger so adding a new worker touches exactly one
# list.
activity_repo = AgentActivityLogRepository(db, org_id=org_id)
active_phase = await activity_repo.get_active_phase_worker(bud.id, PHASE_WORKER_SLUGS)
if active_phase is not None:
bud_data.active_phase_worker = {
"skill_slug": active_phase.skill_slug or "",
"message": active_phase.message or "",
}
# Sticky failure banner: most recent skill_failed newer than the
# user's dismissal timestamp. Covers the restart-recovery and
# missed-WS-event cases without any client-side reconnect logic —
# if the failure happened, the next BUD load surfaces it; the user
# dismisses, the column updates, the banner is gone for good.
latest_failure = await activity_repo.get_latest_skill_failed(
bud.id,
skill_slugs=PHASE_WORKER_SLUGS,
since=bud.phase_failure_acknowledged_at,
)
if latest_failure is not None:
bud_data.last_phase_failure = {
"skill_slug": latest_failure.skill_slug or "",
"message": latest_failure.message or "",
"failed_at": latest_failure.created_at.isoformat()
if latest_failure.created_at
else None,
"metadata": latest_failure.metadata_ or {},
}
# ``has_learning`` is a cheap tab-visibility flag: the BUD detail
# page hides the "Learnings" tab when no feature_learning row has a
# retrospective yet. The full markdown is fetched lazily via
# GET /buds/{id}/learning so the BUD list payload stays small.
learning_row = await FeatureLearningRepository(db, org_id=org_id).get_for_bud(bud.id)
bud_data.has_learning = bool(learning_row and learning_row.retrospective_md)
return bud_data
router = APIRouter(tags=["buds"])
# ── Sub-routers ───────────────────────────────────────────────────
router.include_router(designs_router, prefix="/{bud_id}/designs", tags=["bud-designs"])
router.include_router(estimates_router, prefix="/{bud_id}", tags=["bud-estimates"])
router.include_router(
linked_features_router,
prefix="/{bud_id}/linked-features",
tags=["bud-linked-features"],
)
router.include_router(prs_router, tags=["bud-prs"])
router.include_router(qa_router, prefix="/{bud_id}/qa", tags=["bud-qa"])
router.include_router(workflows_router, prefix="/{bud_id}", tags=["bud-workflows"])
router.include_router(chat_router, prefix="/{bud_id}", tags=["bud-chat"])
router.include_router(todos_router, tags=["bud-todos"])
router.include_router(versions_router, prefix="/{bud_id}", tags=["bud-versions"])
# ── CRUD ──────────────────────────────────────────────────────────
@router.get(
"/",
response_model=list[BUDListItem],
dependencies=[Depends(require_permissions("buds:view"))],
)
async def list_buds(
status_filter: str | None = Query(None, alias="status"),
order_by: Literal["priority"] | None = Query(
None, description="Sort key. Omit for default (bud_number desc)."
),
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> list[BUDDocument]:
"""List BUDs for the current user's organization."""
if status_filter:
try:
BUDStatus(status_filter)
except ValueError:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Invalid status: {status_filter}",
) from None
bud_repo = BUDRepository(db, org_id=current_user.org_id)
buds = await bud_repo.list_buds(
status_filter=status_filter,
order_by_priority=order_by == "priority",
)
# Batch-fetch open bug counts for all BUDs in one query
bug_repo = BugRepository(db, org_id=current_user.org_id)
bug_counts = await bug_repo.open_bug_counts_by_bud([b.id for b in buds])
# Inject open_bug_count as a transient attribute so Pydantic's
# from_attributes picks it up alongside the ORM columns.
for b in buds:
b.open_bug_count = bug_counts.get(b.id, 0) # type: ignore[attr-defined]
return buds
@router.post(
"/",
response_model=BUDRead,
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(require_permissions("buds:create"))],
)
async def create_bud(
body: BUDCreate,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> BUDRead:
"""Create a new BUD with auto-incremented bud_number."""
bud_repo = BUDRepository(db, org_id=current_user.org_id)
next_number = await bud_repo.next_bud_number()
# Empty dict from the schema default = all phases skip. Stored as
# the JSONB literal (not NULL) so the frontend can distinguish a
# freshly-created opt-out from a never-explicitly-set legacy row.
auto_generate_phases = body.auto_generate_phases
bud = BUDDocument(
org_id=current_user.org_id,
bud_number=next_number,
title=body.title,
status=BUDStatus.BUD,
priority=body.priority,
requirements_md=body.requirements_md,
figma_url=body.figma_url,
metadata_=body.metadata_,
auto_generate_phases=auto_generate_phases,
)
await bud_repo.create(bud)
# Persist per-BUD stage skill overrides (Advanced settings on create).
# Validates that each (stage, skill_id) pair points at a skill whose
# agent_type matches the stage's expected agent — wrong picks get a
# 400 instead of silently routing to the wrong skill at run-time.
if body.stage_skill_overrides:
await _persist_stage_skill_overrides(
db,
current_user.org_id,
bud.id,
body.stage_skill_overrides,
)
# Generate embedding so the bug linker can match bugs to this BUD.
# Fast (~50ms) and done inline so the embedding is available immediately.
try:
from app.services.embedding_service import embedding_service
embed_text = body.title
if body.requirements_md:
embed_text = f"{body.title} {body.requirements_md[:500]}"
bud.embedding = await embedding_service.embed(embed_text)
await db.flush()
except Exception:
logger.warning("bud_embedding_failed", bud_number=next_number, exc_info=True)
from app.services.feature_lifecycle import create_planned_feature
await create_planned_feature(
db,
current_user.org_id,
next_number,
body.title,
body.requirements_md or "",
)
# Record timeline + auto-assign
from app.services.bud_assignment import auto_assign_for_phase
from app.services.bud_timeline import record_event
await record_event(
db,
current_user.org_id,
bud.id,
"created",
actor_id=current_user.id,
actor_name=current_user.name,
detail={"source": "web"},
)
await auto_assign_for_phase(
db,
current_user.org_id,
bud,
BUDStatus.BUD,
actor_id=current_user.id,
actor_name=current_user.name,
)
logger.info(
"bud_created",
bud_id=str(bud.id),
bud_number=next_number,
org_id=str(bud.org_id),
auto_generate_phases=auto_generate_phases,
)
# External-LLM mode: each phase is opt-in. Only fire the PM/bud
# agent if the user explicitly enabled the "bud" phase. Missing key
# or False = skip; user supplies the PRD via the section editor
# (typically driven by their local AI through the remote MCP).
if should_auto_generate_phase(auto_generate_phases, "bud"):
await create_agent_task_for_stage(
bud,
"bud",
current_user.org_id,
db,
triggered_by=current_user.id,
force=True,
)
# Estimation deferred — triggers after PRD agent completes (via agent_result_handlers)
return await _bud_response(bud, current_user.org_id, db)
@router.get(
"/{bud_id}",
response_model=BUDRead,
dependencies=[Depends(require_permissions("buds:view"))],
)
async def get_bud(
bud_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> BUDRead:
"""Retrieve a single BUD by ID, including active agent task."""
bud_repo = BUDRepository(db, org_id=current_user.org_id)
bud = await bud_repo.get_by_id(bud_id)
if bud is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="BUD not found")
return await _bud_response(bud, current_user.org_id, db)
@router.get(
"/{bud_id}/timeline",
response_model=list[TimelineEventRead],
dependencies=[Depends(require_permissions("buds:view"))],
)
async def get_bud_timeline(
bud_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> list[BUDTimelineEvent]:
"""Fetch timeline events for a BUD in chronological order."""
repo = BUDTimelineRepository(db, org_id=current_user.org_id)
return await repo.list_for_bud(bud_id)
@router.get(
"/{bud_id}/stage-skill-overrides",
response_model=dict[BUDStatus, uuid.UUID],
dependencies=[Depends(require_permissions("buds:view"))],
)
async def get_stage_skill_overrides(
bud_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> dict[BUDStatus, uuid.UUID]:
"""Return the per-stage skill overrides set on this BUD.
Used by the BUD detail page's "Skills" dialog to render the current
pinned skill for each stage (so the user can see what they previously
picked, plus the default for stages they didn't override).
"""
from app.repositories.bud_stage_skill_override import (
BUDStageSkillOverrideRepository,
)
bud_repo = BUDRepository(db, org_id=current_user.org_id)
bud = await bud_repo.get_by_id(bud_id)
if bud is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="BUD not found")
override_repo = BUDStageSkillOverrideRepository(db, org_id=current_user.org_id)
rows = await override_repo.list_for_bud(bud_id)
return {row.bud_status: row.skill_id for row in rows}
@router.put(
"/{bud_id}/stage-skill-overrides",
response_model=dict[BUDStatus, uuid.UUID],
dependencies=[Depends(require_permissions("buds:edit"))],
)
async def set_stage_skill_overrides(
bud_id: uuid.UUID,
body: dict[BUDStatus, uuid.UUID],
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> dict[BUDStatus, uuid.UUID]:
"""Replace the BUD's per-stage skill overrides in one shot.
The body is the *full* desired map of stage → skill_id. Stages not
present in the body are cleared — that way the same call shape works
for "I added an override", "I changed one", and "I cleared one back
to the org default". Each (stage, skill) pair is validated against
the stage's expected agent type before persisting.
"""
bud_repo = BUDRepository(db, org_id=current_user.org_id)
bud = await bud_repo.get_by_id(bud_id)
if bud is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="BUD not found")
await _persist_stage_skill_overrides(db, current_user.org_id, bud_id, body)
await db.commit()
logger.info(
"bud_stage_skill_overrides_updated",
bud_id=str(bud_id),
org_id=str(current_user.org_id),
count=len(body),
)
return body
@router.get(
"/{bud_id}/learning",
response_model=BUDLearningRead,
dependencies=[Depends(require_permissions("buds:view"))],
)
async def get_bud_learning(
bud_id: uuid.UUID,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> BUDLearningRead:
"""Return the post-close retrospective for this BUD.
Drives the BUD detail "Learnings" tab. Returns 404 when no
FeatureLearning row exists yet — i.e. the BUD hasn't closed, the
Learning Agent hasn't run, or the user opted out via
``auto_generate_phases.closed = false``. The FE gates tab
visibility on ``BUDRead.has_learning`` so this endpoint is only
called after the flag flips true.
"""
bud_repo = BUDRepository(db, org_id=current_user.org_id)
bud = await bud_repo.get_by_id(bud_id)
if bud is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="BUD not found")
learning = await FeatureLearningRepository(db, org_id=current_user.org_id).get_for_bud(bud_id)
if learning is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No learning recorded for this BUD yet",
)
return BUDLearningRead.model_validate(learning)
# Status transitions QA owns directly via PATCH. Matches the manual-testing
# guard further down in update_bud (search for "Manual testing → uat"): QA
# is the final gate out of testing, advancing to uat normally or to prod
# when the org config has UAT disabled. Other transitions (uat → prod,
# sending back to development) remain PM/dev territory.
_QA_OWNED_TRANSITIONS: frozenset[tuple[BUDStatus, BUDStatus]] = frozenset(
{
(BUDStatus.TESTING, BUDStatus.UAT),
(BUDStatus.TESTING, BUDStatus.PROD),
}
)
def _enforce_qa_scope(
perms: set[str], current_status: BUDStatus, update_data: dict[str, Any]
) -> None:
"""Restrict buds:test-only callers to QA-owned status promotions.
Raises 403 if a QA caller tries to update non-status fields or
transition to a status outside ``_QA_OWNED_TRANSITIONS``. Callers
with ``buds:edit`` (PMs, owners) skip this check entirely.
Permissions drive the decision rather than role names so custom
roles that grant ``buds:test`` get the same scope automatically.
"""
if "buds:edit" in perms or "buds:test" not in perms:
return
if set(update_data) != {"status"}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="QA role can only update BUD status, not other fields.",
)
if (current_status, update_data["status"]) not in _QA_OWNED_TRANSITIONS:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=(
f"QA role cannot transition {current_status.value} → "
f"{update_data['status'].value}."
),
)
@router.patch(
"/{bud_id}",
response_model=BUDRead,
# buds:test is accepted so QA users can complete the testing phase
# (testing → uat / prod). Field-level enforcement inside the handler
# restricts buds:test-only callers to that single transition.
dependencies=[Depends(require_permissions("buds:edit", "buds:test", mode="any"))],
)
async def update_bud(
bud_id: uuid.UUID,
body: BUDUpdate,
response: Response,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
) -> BUDRead:
"""Update a BUD (title, status, requirements, tech spec, test plan, metadata)."""
bud_repo = BUDRepository(db, org_id=current_user.org_id)
bud = await bud_repo.get_by_id(bud_id)
if bud is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="BUD not found")
# Capture the full set of fields the caller actually sent BEFORE
# ``update_data`` gets mutated (assignee_id / auto_generate_phases
# are popped out below for special-case handling). The version
# snapshot check at the end of the handler keys off this set so
# an assignee-only PATCH still produces a history row — without
# it the gate would see an empty ``update_data`` and skip.
original_body_keys = set(body.model_dump(exclude_unset=True).keys())
update_data = body.model_dump(exclude_unset=True)
update_data.pop("status_override_reason", None) # consumed separately, not a model field
# priority is NOT NULL on the column; explicit null in the payload would
# silently flip the row to None and fail at the DB. Reject with 400 so
# the client gets a clear signal instead of a 500.
if "priority" in update_data and update_data["priority"] is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="priority cannot be null; omit the field to leave it unchanged",
)
# Capture the pre-edit snapshot AS A DICT here, before any of the
# auto_generate_phases / assignee / status mutations below. The
# actual DB insert happens at the end, after every guard has passed
# — see ``commit_snapshot`` call further down. Splitting build vs
# commit is what keeps revert correct: the snapshot reflects the
# BUD as it was when the request arrived, not the mutation in
# flight.
pre_snapshot = bud_version_repo.build_snapshot(bud)
pre_phase = bud.status
if "status" in update_data:
try:
update_data["status"] = BUDStatus(update_data["status"])
except ValueError:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Invalid status: {update_data['status']}",
) from None
# Field-level QA gate. Runs before any side-effect-producing code
# so a rejected QA request never mutates state.
user_perms = await get_user_permissions(current_user, db)
_enforce_qa_scope(user_perms, bud.status, update_data)
# Guard: closed/discarded BUDs cannot be reopened. Placed before ANY
# side-effect-producing code (transition_feature_for_bud, assignments)
# so a rejected request never mutates state.
if "status" in update_data and bud.status in (BUDStatus.CLOSED, BUDStatus.DISCARDED):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
f"Cannot change status of a {bud.status.value} BUD. Create a new BUD instead."
),
)
# Guard: leaving the design phase while wireframe generation is still
# in flight produces a phase-overlap state where the design task and
# the next-phase task are both active. The per-design cancel path
# walks ``get_active_for_bud`` and can write terminal state to the
# wrong task in that window. Block the transition until every
# ``bud_designs`` row is out of ``generating``. Discard is exempt —
# abandoning the BUD entirely is a legitimate escape hatch.
if (
"status" in update_data
and bud.status == BUDStatus.DESIGN
and update_data["status"] not in (BUDStatus.DESIGN, BUDStatus.DISCARDED)
):
design_repo = BUDDesignRepository(db, org_id=current_user.org_id)
in_flight = await design_repo.count_by_status(bud.id, BUDDesignStatus.GENERATING)
if in_flight > 0:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=(
f"{in_flight} wireframe{'s' if in_flight > 1 else ''} still generating — "
"cancel them or wait for completion before advancing the phase."
),
)
# Phase-edit policy: section-owning fields are only writable while the
# BUD is in their owning phase. Frontend mirrors this rule in
# SECTION_EDIT_STATUS; backend rejects with HTTP 409 here as
# defense-in-depth against direct API calls.
for field in update_data:
assert_section_editable(bud, field)
if "status" in update_data:
from app.services.feature_lifecycle import transition_feature_for_bud
await transition_feature_for_bud(
db,
current_user.org_id,
bud.bud_number,
update_data["status"],
)
# Capture old values BEFORE applying updates
old_status = bud.status
old_assignee_id = bud.assignee_id
old_title = bud.title
# Handle manual assignee_id changes (before status logic which may auto-assign)
if "assignee_id" in update_data:
new_aid = update_data.pop("assignee_id")
if new_aid and new_aid != old_assignee_id:
await assign_bud(
db,
current_user.org_id,
bud,
new_aid,
current_user.id,
current_user.name,
)
elif not new_aid and old_assignee_id:
await unassign_bud(
db,
current_user.org_id,
bud,
current_user.id,
current_user.name,
)
# Record status change + auto-assign
if "status" in update_data:
new_status = update_data["status"]
# Manual code_review → testing:
# If every impacted repo has a merged PR, this is the same as the
# webhook-driven auto-transition — no bypass, no reason needed.
# Only require a reason when the user is genuinely bypassing the
# PR-merge gate (e.g. docs-only changes, manual merges).
if old_status == BUDStatus.CODE_REVIEW and new_status == BUDStatus.TESTING:
from app.services.bud_code_review_status import get_pr_status_summary
repo_statuses = await get_pr_status_summary(db, current_user.org_id, bud)
all_merged = bool(repo_statuses) and all(
r["pr_state"] == "merged" for r in repo_statuses
)
if not all_merged:
reason = body.status_override_reason
if not reason or not reason.strip():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Reason required when manually advancing to testing",
)
from app.services.bud_timeline import record_event as _record
await _record(
db,
current_user.org_id,
bud.id,
"status_override",
actor_id=current_user.id,
actor_name=current_user.name,
detail={
"from": old_status.value,
"to": "testing",
"reason": reason.strip(),
},
)
# Manual testing → uat (or prod when UAT is disabled):
# QA is only "done" when every manual test case has a terminal
# result — pass / fail / blocked / skipped. Advancing past testing
# while any case is still pending would bury real work in an
# un-triaged state. Skipped counts as terminal because it's an
# explicit tester decision ("not applicable"), unlike pending
# which means "never looked at".
#
# This guard intentionally catches testing → prod even when UAT
# IS enabled in the org config — a user manually jumping past UAT
# still needs QA to have signed off on every case. Closing from
# testing is NOT blocked: closed means "abandoning this BUD",
# not "shipping it", so forcing every pending case to be resolved
# would be friction rather than safety.
if old_status == BUDStatus.TESTING and new_status in (
BUDStatus.UAT,
BUDStatus.PROD,
):
pending_cases = [
tc
for tc in (bud.qa_manual_cases or [])
if isinstance(tc, dict) and tc.get("result") == "pending"
]
if pending_cases:
pending_ids = [str(tc.get("id", "?")) for tc in pending_cases[:5]]
more = len(pending_cases) - len(pending_ids)
suffix = f" and {more} more" if more > 0 else ""
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
f"Cannot advance to {new_status.value}: "
f"{len(pending_cases)} manual test case"
f"{'s' if len(pending_cases) != 1 else ''} still pending "
f"({', '.join(pending_ids)}{suffix}). "
f"Mark each as pass, fail, blocked, or skipped in the QA tab first."
),
)
from app.services.bud_assignment import auto_assign_for_phase
from app.services.bud_timeline import record_event
await record_event(
db,
current_user.org_id,
bud.id,
"status_change",
actor_id=current_user.id,
actor_name=current_user.name,
detail={"from": old_status.value, "to": new_status.value},
)
# Apply the status before the side effects so downstream hooks
# and assignment policy see the correct phase.
if old_status != BUDStatus.DEVELOPMENT and new_status == BUDStatus.DEVELOPMENT:
bud.status = new_status
# auto_assign_for_phase sets ``bud.assignee_id`` — must run before
# the dev-transition hook so the hook can assign newly-synced
# TODOs to that lead in the same transaction.
await auto_assign_for_phase(
db,
current_user.org_id,
bud,
new_status,
actor_id=current_user.id,
actor_name=current_user.name,
)
# Same dev-transition side effects fired by approve_tech_arch — see
# backend/app/services/bud_development.py. Synchronously parses
# the tech spec into BUDTodo rows + assigns to the lead; spawns
# a background task for PERT estimation.
if old_status != BUDStatus.DEVELOPMENT and new_status == BUDStatus.DEVELOPMENT:
from app.services.bud_development import on_bud_development_started
await on_bud_development_started(
db,
current_user.org_id,
bud,
actor_id=current_user.id,
actor_name=current_user.name,
)
# Record title change
if "title" in update_data and update_data["title"] != old_title:
from app.services.bud_timeline import record_event
await record_event(
db,
current_user.org_id,
bud.id,
"content_updated",
actor_id=current_user.id,
actor_name=current_user.name,
detail={"section": "title", "old_title": old_title, "new_title": update_data["title"]},
)
old_tech_spec_md = bud.tech_spec_md if "tech_spec_md" in update_data else None
requirements_md_changed = (
"requirements_md" in update_data and update_data["requirements_md"] != bud.requirements_md
)
# auto_generate_phases is MERGED, not replaced. The dialog sends the
# full normalised map today, but if a future BUDStatus phase becomes
# configurable and an older client sends only the four keys it knows
# about, a verbatim setattr would silently drop the new phase to
# False. Merge-with-existing keeps forward compatibility: unknown
# keys are validated out (only BUDStatus values are accepted), known
# keys not in the patch keep their prior value.
if "auto_generate_phases" in update_data:
incoming_phases = update_data.pop("auto_generate_phases") or {}
merged: dict[str, bool] = dict(bud.auto_generate_phases or {})
valid_phase_keys = {s.value for s in BUDStatus}
for key, val in incoming_phases.items():
if key in valid_phase_keys:
merged[key] = bool(val)
else:
logger.warning(
"bud_auto_generate_phases_unknown_key_dropped",
bud_id=str(bud.id),
key=key,
)
bud.auto_generate_phases = merged
# Commit the pre-edit snapshot captured at the top of the handler.
# Runs only when something will actually mutate (an empty payload
# after ``status_override_reason`` is popped means there's nothing
# to roll back to). ``pre_phase`` is the phase the edit happened
# IN — even if this same request advances status, the snapshot
# belongs to the old phase's ring buffer.
# ``original_body_keys`` includes assignee_id / auto_generate_phases /
# status — the early pops left ``update_data`` partial, so we use the
# original key set as the "did the user actually change anything
# snapshot-worthy?" check.
snapshot_worthy_keys = original_body_keys - {"status_override_reason"}
if snapshot_worthy_keys:
await bud_version_repo.commit_snapshot(
db,
bud_id=bud.id,
phase=pre_phase,
snapshot=pre_snapshot,
source=BUDEditSource.UI,
edited_by=current_user.id,
)
for field, value in update_data.items():
setattr(bud, field, value)
await db.flush()
await db.refresh(bud)
# External-LLM mode: when a user pastes locally-generated PRD
# content into requirements_md, parse the trailing
# {"linked_feature_ids": [...]} JSON fence the prompt instructs the
# LLM to emit. Without this hook the BYO-AI flow would produce BUD
# text with the fence but no actual BUDFeatureLink rows in the DB,
# so downstream Designer / TechPlanner agents (and the dependency
# map) wouldn't see what features the user linked. Mirrors the
# PM-agent result-handler path; uses MANUAL source so audit and
# timeline distinguish human-driven from agent-driven links.
if requirements_md_changed and update_data.get("requirements_md"):
await persist_linked_features_from_markdown(
bud.id,
current_user.org_id,
update_data["requirements_md"],
db,
source=BUDFeatureLinkSource.MANUAL,
actor_name=current_user.name or current_user.email,
actor_id=current_user.id,
)
# If the developer edited tech_spec_md on a DEVELOPMENT-phase BUD,
# refresh the Implementation TODO section (LLM patch when the diff
# extends beyond the section) and re-derive BUDTodo rows. The
# reconciler preserves in-flight developer work.
if "tech_spec_md" in update_data and update_data["tech_spec_md"] != old_tech_spec_md:
from app.services.tech_planner_patch import apply_tech_spec_edit
# apply_tech_spec_edit mutates ``bud.tech_spec_md`` in place when
# the patch flow rewrites the section, so the caller's commit
# persists it without a second write here. ``sync_todos_for_bud``
# already flushes newly-inserted BUDTodo rows.
await apply_tech_spec_edit(
bud=bud,
old_spec=old_tech_spec_md,
new_spec=update_data["tech_spec_md"],
db=db,
org_id=current_user.org_id,
)
# Award XP for BUD completion (prod or closed with assignee)
if "status" in update_data:
_completed = update_data["status"] in (BUDStatus.PROD, BUDStatus.CLOSED)
if _completed and bud.assignee_id and old_status not in (BUDStatus.PROD, BUDStatus.CLOSED):
try:
from app.services.xp_service import award_quality_bonus, award_xp
await award_xp(
db,
user_id=bud.assignee_id,
org_id=current_user.org_id,
amount=50,
source="bud_completed",
source_ref=f"bud:{bud.bud_number}",
)
await award_quality_bonus(
db,
user_id=bud.assignee_id,
org_id=current_user.org_id,
bud_id=bud.id,
)
except Exception:
logger.warning("xp_award_failed_bud_completion", exc_info=True)
# Post-closure side-effects: XP, SP, learning metrics, Learning Agent
if _completed:
try:
from app.services.bud_closure import on_bud_closed
await on_bud_closed(
db,
current_user.org_id,
bud,
actor_id=current_user.id,
actor_name=current_user.name,
)
except Exception:
logger.warning("bud_closure_side_effects_failed", exc_info=True)