Skip to content

feat(llc): hierarchy refusals are 422, rules and violation report served and shown, backlog load fixes (#20936, #21032) - #21062

Merged
mrveiss merged 20 commits into
mainfrom
issue-20936
Nov 9, 2026
Merged

mrveiss merged 20 commits into
mainfrom
issue-20936

Conversation

@mrveiss

@mrveiss mrveiss commented Nov 7, 2026 •

Copy link
Copy Markdown
Owner

Closes #20936
Closes #21032

Thinking Path

#20936 closes the two unmet #18978 criteria: a hierarchy breach is answered 422 (not 400), and the rule table and the existing-violation report are served and shown. #21032 is the minor review findings from the #20947 train PR, in the same files.

Single-issue rationale

Two issues, one PR, because they touch the same files (work_item_hierarchy.py, its tests, BacklogView.vue, en.json). Separate PRs would conflict on every one of them.

What Changed

#20936

  • Create and update answer HierarchyViolation (including ProjectRequired) with 422; any other ValueError stays 400 (write_refusal in llc/api/_common.py).
  • New GET /api/llc/work-items/hierarchy-rules and GET /api/llc/work-items/hierarchy-violations, with Pydantic response models. Both check company access first (404 across companies, as the list route does). The report is gated by the existing require_company_admin_unless_platform (403 otherwise), with no new admin-named function.
  • They live on their own router, included before work_items_router, because work_items.py is at its line baseline and the /{work_item_id} capture must not shadow them.
  • useWorkItemHierarchy (typed from the generated contract, full /api/llc/... paths) and BacklogHierarchyPanel: a read-only "Hierarchy rules" section and an admin-only collapsible "Hierarchy violations" section. api.ts regenerated last.
  • Deviation: the admin gate is server-side only. There is no client-side company-role check, so the violations section stays hidden on a 401/403, following the StuckFileCleanupPanel pattern.

#21032

  • move_subtree_to_project writes in bounded batches in the same transaction; a failing later discovery query issues no update.
  • Behavioural checkout test for a user-assigned item.
  • useBacklogItems: request-sequence guard on the list and isLoading, plus a distinct fetch-failure state with a Retry; the create-refresh warning is cleared on a company change.
  • A refused Kanban move rolls back the current card, found by id.
  • A vitest for the llc.enums label mapping in workItemTypes.ts.
  • Bulk sprint assignment moved to BacklogBulkAssignModal, which takes BacklogView under 600 lines, so its size exemption is retired. Fragmentation baselines lowered (modal 25 to 24, distinct classes 5324 to 5323).

Verification

  • Backend llc/ + tests/unit/llc/ at -n 2: 3594 passed, 2 skipped.
  • Guards (fast-guard list, one-admin-gate, unconnected-code, inline-lazy-singleton, file-size, fragmentation, api-contract, hardcoded-literal, i18n): 240 passed.
  • Vitest views/llc, components/llc, composables/llc: 92 files, 814 passed.
  • eslint clean on touched files; black, isort and flake8 clean.
  • The local checkout lacks reka-ui, so the local vitest run used a temporary config aliasing it to a stub. That config was deleted and is not committed; CI uses the real package.

Review fixes

  • 401 vs 403: only a 403 hides the violations section; a 401 (expired session) stays visible as a retryable failure while the shared client's 401 policy re-authenticates (useWorkItemHierarchy.ts).
  • Company change: reset() clears rules, violations, error and hidden state and invalidates in-flight requests before the new fetch.
  • Retry buttons in BacklogView.vue are BaseButton.
  • Reason text: find_hierarchy_violations returns a stable code (parent_cycle, parent_missing, parent_type_not_allowed, project_mismatch, project_required) plus type and parent_type; the panel renders llc.backlog.hierarchyReason.<code> from en.json. English reason kept for logs and API consumers. types/generated/api.ts regenerated.
  • Bounded report: the rules and the limit are applied in SQL (recursive CTE for cycles); AUTOBOT_LLC_HIERARCHY_VIOLATIONS_LIMIT (default 500, range 1-5000); the response carries truncated and the panel shows a translated "showing first N" note.
  • Review follow-up (10d1427): reason text made article-neutral; tests for self-parent, tail into a cycle, chain deeper than 32, cross-company parent (each reported once), PostgreSQL rendering of the recursive CTE, and filter/label agreement for every code.

Model Used

Claude Sonnet 5.5

🤖 Generated with Claude Code

… sequence, show fetch failures, roll back the current Kanban card (#21032)

- move_subtree_to_project updates descendants in SUBTREE_UPDATE_BATCH-sized
  statements in the caller's transaction (one IN over >32,767 ids exceeds the
  bind-parameter limit); a failing later discovery query issues no update.
- A behavioural checkout test: an unlocked user-assigned item ends with a null
  user id, the agent id and assignee type agent.
- useBacklogItems: only the latest request writes the list, isLoading and the new
  loadFailed state; BacklogView shows the failure with a Retry instead of
  "No items match" and drops the create-refresh warning on a company change.
- Kanban: a refused move rolls back the current card, found by id.
- Bulk sprint assignment leaves BacklogView for BacklogBulkAssignModal (on the kit
  form field), which takes BacklogView under the 600-line limit: its size
  exemption is retired. The native-control classes are shared in controlClass.ts.
- A vitest for the llc.enums label mapping in workItemTypes.ts.
…on report are served and shown in the Backlog view (#20936)

- Create and update answer a HierarchyViolation (including ProjectRequired) with
  422; any other ValueError stays 400 (write_refusal in api/_common.py).
- GET /api/llc/work-items/hierarchy-rules serves the parent-type table built from
  ALLOWED_PARENT_TYPES / PROJECT_REQUIRED_TYPES; GET .../hierarchy-violations
  returns find_hierarchy_violations for company owners/admins and platform
  admins (403 otherwise). Both check company access first (404 across companies,
  as the list route does) and are included before work_items.router so the
  /{work_item_id} capture cannot shadow them.
- useWorkItemHierarchy reads both on the generated contract types; the Backlog
  view gets a read-only "Hierarchy rules" section and an admin-only collapsible
  "Hierarchy violations" section (BacklogHierarchyPanel). api.ts regenerated.
@coderabbitai

coderabbitai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 30 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 85d5d2e and 96cbfb4.

Files ignored due to path filters: 1

  • autobot-frontend/src/types/generated/api.ts is excluded by !**/generated/**
Files selected for processing: 29

  • autobot-backend/llc/api/__init__.py
  • autobot-backend/llc/api/_common.py
  • autobot-backend/llc/api/work_item_hierarchy_routes.py
  • autobot-backend/llc/api/work_items.py
  • autobot-backend/llc/services/work_item_hierarchy.py
  • autobot-backend/llc/tests/test_move_subtree_batching_21032.py
  • autobot-backend/llc/tests/test_work_item_hierarchy_18978.py
  • autobot-backend/llc/tests/test_work_item_hierarchy_report_20936.py
  • autobot-backend/llc/tests/test_work_item_hierarchy_routes_20936.py
  • autobot-backend/tests/unit/llc/test_checkout_excludes_user_assigned_15964.py
  • autobot-frontend/src/components/llc/BacklogBulkAssignModal.vue
  • autobot-frontend/src/components/llc/BacklogCreateModal.vue
  • autobot-frontend/src/components/llc/BacklogHierarchyPanel.vue
  • autobot-frontend/src/components/llc/__tests__/BacklogHierarchyPanel.test.ts
  • autobot-frontend/src/components/llc/controlClass.ts
  • autobot-frontend/src/composables/llc/__tests__/useBacklogItems.test.ts
  • autobot-frontend/src/composables/llc/__tests__/useWorkItemHierarchy.test.ts
  • autobot-frontend/src/composables/llc/useBacklogItems.ts
  • autobot-frontend/src/composables/llc/useWorkItemHierarchy.ts
  • autobot-frontend/src/i18n/locales/en.json
  • autobot-frontend/src/views/llc/BacklogView.vue
  • autobot-frontend/src/views/llc/KanbanBoardView.vue
  • autobot-frontend/src/views/llc/__tests__/BacklogView.companyChange.test.ts
  • autobot-frontend/src/views/llc/__tests__/KanbanBoardView.items.test.ts
  • autobot-frontend/src/views/llc/__tests__/workItemTypes.test.ts
  • autobot_shared/env_registry_llc.py
  • docs/developer/ENV_VARS.md
  • repo_tests/frontend_fragmentation_ratchet_test.py
  • scripts/frontend_file_size_known_large.py
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@mrveiss mrveiss added this to the M2 - Company OS workflow-ready milestone Nov 7, 2026
@mrveiss mrveiss added area: company-os Wave 4 · cluster A — Company OS & LLC canvas phase:M2.3 Goals and work hierarchy labels Nov 7, 2026
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Notice: 29 open PRs — past the runaway threshold (25)

This is not a request to defer this PR. There is no cap on open PRs (#19397) -- nothing blocks opening or pushing a PR.

This notice only means the count is high enough to be worth a glance for a runaway — something opening PRs in a loop, or a merge pipeline that has stalled so nothing is draining.

Currently open:

If the queue is draining normally, ignore this. Otherwise:

  1. Check whether CI is dispatching at all — see the ci-dispatch-watchdog status on these PRs
  2. Approved PRs land through the merge train the coordinator sequences (merge commits, never squash) -- check the open chore(merge-train) PR is moving, not each PR on its own
  3. Look for a loop opening near-identical PRs

Warn-only runaway detector — .github/workflows/pr-queue-gate.yml. It never blocks a merge.

@mrveiss

mrveiss commented Nov 7, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) at d4d6acb

Verdict: APPROVE. No blocking finding. 26 changed files, 0 behind main, 0 unresolved review threads. The findings below are advisory (L = fix in this PR if cheap, otherwise follow-up) plus one owner decision.

# Severity Where Finding Suggested fix
1 Owner decision llc/api/work_item_hierarchy_routes.py (violations route); useWorkItemHierarchy.ts The admin gate is server-side only: assert_company_access (404 cross-tenant, platform admin exempt) then require_company_admin_unless_platform (403). The GUI adds no gate of its own and only hides the section on 401/403. This is the right place for enforcement and matches StuckFileCleanupPanel; the open question is whether a client-side role check is also wanted (it would be cosmetic only). Recommend: keep server-only. Owner to confirm.
2 Info get_hierarchy_violations The inline require_company_admin_unless_platform is NOT a twice-defined violation. It is a service-layer function in llc/services/authz.py, not a FastAPI dependency, and company_teams.py, company_ceo.py, approvals.py and budget.py call it the same way (try, then NotAuthorisedError mapped to 403). Tenant isolation holds: rules need a same-company member, violations need owner/admin, another company's data is a 404 for non-platform callers. None.
3 Low useWorkItemHierarchy.ts isNotAdmin A 401 (expired session) is treated as "not an admin" and silently hides the report. Treat only 403 as refused; let 401 fall to the global auth handling, or show the failed state.
4 Low useWorkItemHierarchy.ts On company change rules and violations keep the previous company's rows until the new response arrives (seq guard stops the stale write but nothing clears them at start). Clear both at the start of the load when companyId changed.
5 Low BacklogView.vue fetch-failed alert Retry is a raw <button class="underline">, while the new panel and modals use kit BaseButton. Use BaseButton variant="secondary" size="sm".
6 Low BacklogHierarchyPanel.vue row.reason is a server English string shown raw. It is not a hardcoded UI literal (all labels use t()), but it will not localize when other locales arrive. Follow-up: return a reason code and map it to an i18n key.
7 Low find_hierarchy_violations Loads every work item of the company into memory with no bound; the report can be slow on a large company. Pre-existing function, new route exposes it. Follow-up: page or stream, or cap the returned rows with a truncated flag.

Verified against code, no finding:

  • 422/400: write_refusal in _common.py maps HierarchyViolation (and its subclass ProjectRequired) to 422 and any other ValueError to 400; parametrized create and update tests cover both.
  • Route order: hierarchy router included before work_items_router in api/__init__.py, with a test pinning it.
  • 10k batching: _descendant_ids finishes discovery before the first write, writes run through the caller's session (same transaction, so atomic); a test pins that a failing later query issues no update, plus a batch-size-under-bind-limit test.
  • useBacklogItems: latest sequence guards items, isLoading and loadFailed; a superseded request returns true and never touches state; a failed first load for a new company clears the old company's rows. Correct.
  • Kanban rolls back the current card by id and only if it is still in the column this move put it in.
  • Sizes: BacklogView 516, KanbanBoardView 594 (both at most 600); the BacklogView exemption is retired and the class-count baselines are lowered with a stated reason. No fixed sleeps, no line-number comments found in the added lines. New UI strings are t() keys; the extracted modal uses BaseModal, BaseFormField, BaseButton.

Issue ACs: #20936 AC1 to AC3 met (tests present); AC4 (unconnected-code gate) is satisfied by the frontend composable calling both routes through the generated paths types. #21032: all seven items have code and a test.

…lears rows, BaseButton retry, translated reason codes, SQL-bounded report (#20936)
@mrveiss

mrveiss commented Nov 7, 2026

Copy link
Copy Markdown
Owner Author

Code review (code-reviewer pass) at c39b62e

Verdict: APPROVE. Delta d4d6acb..c39b62e is one commit. The SQL rewrite matches the old Python logic for all five codes (hand-traced), the CTE terminates, and nothing crosses a company. The findings below are non-blocking. Branch is 78 commits behind main; the train rebases it.

# Sev Area Finding Fix
1 Medium Tests / dialect The report tests run only on SQLite. The CTE uses no arrays, ANY or path strings (integer depth plus node != start), so I see no dialect-specific syntax. But the PostgreSQL rendering is unexercised: the typed literal(1) seed in a recursive union and the IN (recursive CTE) in both the select list and the WHERE clause. CI cannot catch a PostgreSQL-only error here. Compile the statement with the PostgreSQL dialect in a test and assert it renders WITH RECURSIVE, or run one PostgreSQL-backed test.
2 Medium Tests The cycle cases are thin. Only the 2-cycle is covered. Missing: a self-parent (traced by hand: seed row has node == start, so CYCLE, fine), a tail row pointing into a cycle (flagged CYCLE after 32 hops, same as the old _in_cycle), a chain deeper than 32, and a parent_id into another company's row (traced: reported parent_missing, never walked). Add these four cases.
3 Low Perf The CTE has no LIMIT. It walks up to 32 ancestors per company row before the outer LIMIT n+1 applies, so SQL bounds the transfer but not the walk. That is O(depth x rows), about 5N for legal trees and at most 32N for cyclic data. Acceptable. Note it in the docstring.
4 Low Correctness _row_violation falls through to PROJECT_REQUIRED and relies on _violation_filter having already matched. If the two ever drift, a row is silently mislabelled. Add a parametrised test that feeds each code's row to both, or raise on an unreachable fall-through.
5 Nit i18n The en string renders "A Task cannot sit under a Epic." and the test pins it. Reword to "{type} cannot sit under {parentType}."
6 Info Semantics LIMIT n+1 and truncated are correct (fetched[:limit], len > limit). ORDER BY identifier, id is stable across calls. There is no offset or cursor, so rows past the limit are unreachable. The UI says so. None.

Verified OK

  • Parent cycle. Self-parent and 2-cycle end at node == start. An N-cycle ends the same way. A tail into a cycle, or any chain over 32, ends at depth 32. Each row appears once, because membership goes through IN (subquery), not a join.
  • Other codes. parent_missing, parent_type_not_allowed, project_mismatch and project_required match the old logic, including the empty allowed set for epics and a NULL project, which is_distinct_from handles.
  • Company scoping. Company scoping is enforced in the CTE seed, in the recursive step, and in the parent outer-join.
  • Env var. AUTOBOT_LLC_HIERARCHY_VIOLATIONS_LIMIT is registered (default 500, range 1-5000) and has a row in ENV_VARS.md.
  • Frontend.
    • 401 no longer hides the section; only 403 does, and a 401 shows as a retryable failure.
    • reset() bumps both sequence counters, so late answers from the old company are ignored.
    • Retry buttons use BaseButton.
    • Reason text goes through llc.backlog.hierarchyReason.<code>, with all five keys in en.json and a fallback to the server text for an unknown code.
    • api.ts carries code, type, parent_type and truncated.
  • Hygiene.
    • No fixed sleeps or line-number comments.
    • work_item_hierarchy.py is 364 lines.
    • New functions are under 30 lines.

@mrveiss

mrveiss commented Nov 7, 2026

Copy link
Copy Markdown
Owner Author

Code review (delta check) at 10d1427, after APPROVE at c39b62e. One own commit (10d1427023; d9339cb655 is an auto-sync of main). work_item_hierarchy.py only extracts the SELECT into violations_statement(company, limit) so it can be compiled. There is no behaviour change. The new tests cover: a self-parent cycle reported once, a tail into a cycle, a chain deeper than the limit, a cross-company parent (parent_missing, never walked), PostgreSQL-dialect rendering, and a parametrised filter-to-code agreement. The reason text is article-neutral. All four requested items are delivered. The verdict stays APPROVE.

@mrveiss

mrveiss commented Nov 9, 2026

Copy link
Copy Markdown
Owner Author

Delta review: 10d1427 after approved c39b62e. Verdict: APPROVE

Severity File:line Finding Fix
none autobot-backend/llc/services/work_item_hierarchy.py:309 Extracts violations_statement so the SELECT can be compiled in tests; find_hierarchy_violations is behaviour-identical and both functions are under 30 lines -
none autobot-frontend/src/i18n/locales/en.json:8800 Article dropped from the reason keys so the text is correct for 'Epic'/'Issue'; the test string was updated to match; no other consumers of the old text -
low test_work_item_hierarchy_report_20936.py (test_the_statement_renders_for_postgresql) Asserts on rendered SQL substrings (e.g. %(param_1)s AS depth), which will break on a SQLAlchemy upgrade Acceptable as a render guard; loosen if it becomes noisy
none same file, cycle/limit/foreign-company cases + parametrized SQL-vs-Python code agreement Real coverage added with a control for each shape; no counts repinned -

@mrveiss

mrveiss commented Nov 9, 2026

Copy link
Copy Markdown
Owner Author

Merge check at 21e6326: MERGE-OK. The three merge commits (21e6326, b6653ff, b4613af) have no combined hunks, so every file came cleanly from one side. Against main, the ratchet diff only lowers two pins this branch earns: distinct_class_names 5322→5321 and modal 25→24 (the bulk-assign modal moved onto the kit form field). Main's ceilings report STALE on this branch's own improvement, which is the #20414 case. Nothing is raised.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

✅ SSOT Configuration Compliance: Passing

🎉 No new hardcoded values of either class — ssot and other both block.

Known backlog in pipeline-scripts/hardcoded_values_baseline.txt is suppressed and tracked in #14371.

@mrveiss
mrveiss merged commit fc86c45 into main Nov 9, 2026
3 checks passed
mrveiss added a commit that referenced this pull request Nov 9, 2026
@mrveiss
mrveiss deleted the issue-20936 branch November 9, 2026 23:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: company-os Wave 4 · cluster A — Company OS & LLC canvas phase:M2.3 Goals and work hierarchy

Projects

None yet

1 participant