Skip to content

1.5.6.1#83

Closed
cj-vana wants to merge 4 commits into
betafrom
cj-prs
Closed

1.5.6.1#83
cj-vana wants to merge 4 commits into
betafrom
cj-prs

Conversation

@cj-vana

@cj-vana cj-vana commented Sep 10, 2025

Copy link
Copy Markdown
Collaborator

PR Type

Enhancement


Description

Code Quality Infrastructure: Added comprehensive CI/CD pipeline with ESLint, Ruff, and SQLFluff linting for TypeScript, Python, and SQL code
Modern Python Compatibility: Updated Python capture agent to use Python 3.11+ syntax including datetime.UTC and modern type hints (list[T] instead of List[T])
Extensive SQL Formatting: Standardized formatting across 50+ database migrations with consistent 4-space indentation, explicit JOIN syntax, and proper JSONB formatting
ESLint Configuration: Added legacy code compatibility rules while maintaining quality standards for new development
Documentation Updates: Enhanced CONTRIBUTING.md with CodeRabbit AI assistant integration and added comprehensive CHANGELOG.md for version 1.5.6.1
Variable Mutability Fixes: Changed let to const declarations for immutable objects across React components
SQL Syntax Fixes: Added missing semicolons and newlines, fixed table reference issues in RLS policies


Diagram Walkthrough

flowchart LR
  A["Legacy Codebase"] --> B["CI/CD Pipeline"]
  B --> C["Multi-Language Linting"]
  C --> D["ESLint (TypeScript)"]
  C --> E["Ruff (Python)"]
  C --> F["SQLFluff (SQL)"]
  A --> G["Code Formatting"]
  G --> H["Python Modernization"]
  G --> I["SQL Standardization"]
  G --> J["React Improvements"]
  B --> K["Quality Gates"]
  K --> L["Automated Checks"]
Loading

File Walkthrough

Relevant files
Formatting
52 files
main.py
Import organization and timezone compatibility updates     

agents/capture-agent-py/main.py

• Reordered import statements alphabetically for better organization

Updated timezone reference from datetime.timezone.utc to datetime.UTC
for Python 3.11+ compatibility
• Applied consistent code formatting
with proper spacing and indentation

+36/-36 
dsp.py
Import reorganization and formatting improvements               

agents/capture-agent-py/capture_agent/dsp.py

• Reorganized imports alphabetically and grouped related imports
together
• Fixed minor whitespace formatting issues for consistency

Maintained existing functionality while improving code organization

+16/-14 
server.py
Import consolidation and modern type hints                             

agents/capture-agent-py/capture_agent/server.py

• Consolidated imports and reorganized them for better readability

Updated type hints to use modern Python syntax
(set[WebSocketServerProtocol] instead of Set)
• Applied consistent
formatting and spacing throughout the file

+11/-15 
schema.py
Modern type hints and import organization                               

agents/capture-agent-py/capture_agent/schema.py

• Updated type hints to use modern Python syntax (list[float] instead
of List[float])
• Reorganized imports to follow Python conventions

Applied consistent formatting and spacing

+10/-8   
generate_cert.py
Import organization and formatting cleanup                             

agents/capture-agent-py/generate_cert.py

• Reordered imports alphabetically for consistency
• Applied minor
formatting improvements with proper spacing

+4/-3     
audio.py
Modern imports and type hints update                                         

agents/capture-agent-py/capture_agent/audio.py

• Updated imports to use modern Python syntax and organization

Changed type hints to use built-in types (list[Device] instead of
List[Device])
• Added proper import grouping and spacing

+7/-4     
__main__.py
Import formatting improvements                                                     

agents/capture-agent-py/capture_agent/main.py

• Added proper import spacing and organization
• Applied consistent
formatting with blank lines

+2/-0     
20250605170000_add_update_rls_for_shared_edits.sql
SQL formatting and JOIN syntax improvements                           

supabase/migrations/20250605170000_add_update_rls_for_shared_edits.sql

• Reformatted SQL policies with consistent indentation and line breaks

• Changed JOIN syntax to use explicit INNER JOIN for clarity
• Applied
consistent formatting across all RLS policies for patch_sheets,
stage_plots, run_of_shows, and production_schedules

+108/-100
20250605165000_update_rls_for_claimed_shares.sql
SQL formatting and explicit JOIN syntax                                   

supabase/migrations/20250605165000_update_rls_for_claimed_shares.sql

• Applied consistent SQL formatting with proper indentation
• Updated
JOIN syntax to use explicit INNER JOIN statements
• Improved
readability of RLS policies across multiple tables

+85/-81 
20250612120000_update_share_for_theater_mic_plots.sql
SQL formatting improvements for theater mic plots               

supabase/migrations/20250612120000_update_share_for_theater_mic_plots.sql

• Reformatted SQL policies with consistent indentation and spacing

Updated JOIN syntax to use explicit INNER JOIN for better clarity

Applied consistent formatting across theater mic plot RLS policies

+71/-63 
20250425212102_tiny_shore.sql
SQL formatting standardization for shared links                   

supabase/migrations/20250425212102_tiny_shore.sql

• Applied consistent SQL formatting with proper indentation and
spacing
• Standardized column definitions and constraint formatting

Improved readability of table creation and policy definitions

+75/-71 
20250814180000_create_leq_measurements.sql
SQL formatting and PostgreSQL syntax improvements               

supabase/migrations/20250814180000_create_leq_measurements.sql

• Standardized SQL formatting with consistent indentation and case
usage
• Updated function syntax to use proper PostgreSQL conventions

Applied consistent formatting to table creation, policies, and
triggers

+40/-40 
20250817124300_create_tf_measurements.sql
SQL formatting improvements for TF measurements                   

supabase/migrations/20250817124300_create_tf_measurements.sql

• Applied consistent indentation and formatting to table creation

Standardized policy names and formatting across all RLS policies

Improved readability of column definitions and constraints

+49/-49 
20250612100000_add_corporate_mic_plots_to_share_links.sql
SQL formatting improvements for corporate mic plots           

supabase/migrations/20250612100000_add_corporate_mic_plots_to_share_links.sql

• Reformatted SQL with consistent indentation and spacing
• Updated
JOIN syntax to use explicit table aliases
• Applied consistent
formatting to RLS policies and constraints

+46/-43 
20250429043238_long_term.sql
SQL formatting standardization for shared policies             

supabase/migrations/20250429043238_long_term.sql

• Applied consistent SQL formatting with proper indentation

Standardized WHERE clause formatting and boolean conditions
• Improved
readability of shared link policies and functions

+46/-46 
20250605140000_add_live_data_to_run_of_shows_and_sharing_rpc.sql
SQL function formatting improvements                                         

supabase/migrations/20250605140000_add_live_data_to_run_of_shows_and_sharing_rpc.sql

• Reformatted function definition with consistent indentation

Applied proper SQL formatting to the RPC function structure
• Improved
readability of the complex function logic

+21/-21 
20250430100000_create_production_schedules.sql
SQL formatting improvements for production schedules         

supabase/migrations/20250430100000_create_production_schedules.sql

• Applied consistent SQL formatting with proper indentation and
spacing
• Standardized table creation syntax and column definitions

Improved formatting of RLS policies and trigger definitions

+29/-28 
20250429041941_wandering_stream.sql
SQL formatting standardization for shared access                 

supabase/migrations/20250429041941_wandering_stream.sql

• Applied consistent SQL formatting with proper indentation

Standardized policy formatting and WHERE clause structure
• Improved
readability of shared access policies

+46/-46 
20250429040931_polished_glade.sql
SQL formatting improvements for shared resources                 

supabase/migrations/20250429040931_polished_glade.sql

• Applied consistent SQL formatting with proper indentation

Standardized policy structure and WHERE clause formatting
• Improved
readability of shared resource policies

+42/-42 
20250428175017_lucky_shape.sql
SQL formatting standardization for shared policies             

supabase/migrations/20250428175017_lucky_shape.sql

• Applied consistent SQL formatting with proper indentation and
spacing
• Standardized policy formatting across all shared resource
policies
• Improved readability of WHERE clauses and boolean
conditions

+42/-42 
20250428180538_late_voice.sql
SQL formatting improvements for shared access                       

supabase/migrations/20250428180538_late_voice.sql

• Applied consistent SQL formatting with proper indentation

Standardized policy structure and WHERE clause formatting
• Improved
readability of shared access policies

+42/-42 
20250429050554_withered_queen.sql
SQL formatting improvements for shared link functions       

supabase/migrations/20250429050554_withered_queen.sql

• Applied consistent SQL formatting with proper indentation

Standardized function parameter formatting and return types
• Improved
readability of function definitions and policy structures

+25/-25 
20250604100000_create_run_of_show_table.sql
SQL formatting improvements for run of show table               

supabase/migrations/20250604100000_create_run_of_show_table.sql

• Applied consistent SQL formatting with proper indentation and
spacing
• Standardized table creation syntax and column definitions

Improved formatting of RLS policies and index creation

+32/-32 
PrintStagePlotExport.tsx
Variable declaration improvements for style objects           

apps/web/src/components/PrintStagePlotExport.tsx

• Changed variable declarations from let to const for immutable style
objects
• Applied consistent variable naming for elementStyle,
wrapperStyle, innerStyle, symbolStyle, and labelStyle
• Improved code
consistency and immutability practices

+5/-5     
20250605141700_update_shared_links_constraint_and_ros_rls.sql
SQL formatting improvements for shared links constraints 

supabase/migrations/20250605141700_update_shared_links_constraint_and_ros_rls.sql

• Applied consistent SQL formatting with proper indentation

Standardized policy structure and WHERE clause formatting
• Improved
readability of constraint updates and RLS policies

+30/-29 
20250611100000_create_corporate_mic_plots.sql
SQL formatting improvements for corporate mic plots table

supabase/migrations/20250611100000_create_corporate_mic_plots.sql

• Applied consistent SQL formatting with proper indentation and
spacing
• Standardized table creation syntax and column definitions

Improved formatting of RLS policies and constraint definitions

+32/-32 
20250612000000_create_theater_mic_plots.sql
SQL formatting improvements for theater mic plots table   

supabase/migrations/20250612000000_create_theater_mic_plots.sql

• Applied consistent SQL formatting with proper indentation and
spacing
• Standardized table creation syntax and column definitions

Improved formatting of RLS policies and constraint definitions

+32/-32 
20250428173152_silent_swamp.sql
SQL formatting standardization for shared resource policies

supabase/migrations/20250428173152_silent_swamp.sql

• Applied consistent SQL formatting with proper indentation

Standardized policy structure and WHERE clause formatting
• Improved
readability of shared resource access policies

+42/-42 
20250428173008_copper_shadow.sql
SQL formatting improvements for shared access policies     

supabase/migrations/20250428173008_copper_shadow.sql

• Applied consistent SQL formatting with proper indentation

Standardized policy structure and WHERE clause formatting
• Improved
readability of shared access policies

+42/-42 
20250428173327_precious_tower.sql
SQL formatting standardization for shared resources           

supabase/migrations/20250428173327_precious_tower.sql

• Applied consistent SQL formatting with proper indentation

Standardized policy structure and WHERE clause formatting
• Improved
readability of shared resource policies

+42/-42 
20250423215435_soft_sunset.sql
SQL formatting improvements for stage plots table               

supabase/migrations/20250423215435_soft_sunset.sql

• Applied consistent SQL formatting with proper indentation and
spacing
• Standardized table creation syntax and column definitions

Improved formatting of RLS policies and constraint definitions

+23/-23 
20250423184330_dusty_spark.sql
Standardize SQL indentation to 4-space format                       

supabase/migrations/20250423184330_dusty_spark.sql

• Standardized indentation for CREATE TABLE statement and RLS policies

• Changed from 2-space to 4-space indentation throughout the file

Improved code formatting consistency for patch_sheets table creation
and policies

+22/-22 
20250429043444_super_recipe.sql
Format SQL function parameters and policies consistently 

supabase/migrations/20250429043444_super_recipe.sql

• Updated function parameter indentation to 4-space format

Standardized RLS policy formatting with consistent indentation

Applied consistent formatting to all CREATE POLICY statements

+19/-19 
20250429050413_peaceful_paper.sql
Standardize function formatting and language specification

supabase/migrations/20250429050413_peaceful_paper.sql

• Standardized function parameter and return table indentation

Changed LANGUAGE SQL to lowercase LANGUAGE sql
• Applied 4-space
indentation throughout the migration file

+16/-16 
20250429045511_lucky_portal.sql
Format function parameters and standardize boolean values

supabase/migrations/20250429045511_lucky_portal.sql

• Updated function parameters to use 4-space indentation

Standardized RLS policy formatting with consistent indentation

Changed boolean values from lowercase to uppercase (FALSE, TRUE)

+19/-19 
20250429050131_jade_gate.sql
Standardize function formatting and language specification

supabase/migrations/20250429050131_jade_gate.sql

• Applied 4-space indentation to function definitions and return
tables
• Changed LANGUAGE SQL to lowercase LANGUAGE sql
• Standardized
formatting throughout the migration file

+16/-16 
20250503100000_add_production_schedule_to_shared_links_check.sql
Format production schedule shared links policies consistently

supabase/migrations/20250503100000_add_production_schedule_to_shared_links_check.sql

• Standardized RLS policy formatting with 4-space indentation
• Added
table aliases (AS sl) to subqueries for clarity
• Improved SQL
formatting consistency throughout the file

+23/-21 
20250605163000_create_userclaimed_shares_table.sql
Standardize user claimed shares table formatting                 

supabase/migrations/20250605163000_create_userclaimed_shares_table.sql

• Applied 4-space indentation to CREATE TABLE statement
• Standardized
RLS policy formatting with consistent indentation
• Improved overall
code formatting for the user claimed shares table

+17/-17 
20250605164000_create_rpc_get_user_claimed_documents.sql
Format RPC function definition with consistent indentation

supabase/migrations/20250605164000_create_rpc_get_user_claimed_documents.sql

• Standardized function definition formatting with 4-space indentation

• Applied consistent indentation to RETURNS TABLE and function body

Improved overall SQL formatting consistency

+15/-15 
20250905123341_add_foreign_key_beltpacks_to_transceivers.sql
Format beltpacks foreign key migration consistently           

supabase/migrations/20250905123341_add_foreign_key_beltpacks_to_transceivers.sql

• Standardized RLS policy formatting with 4-space indentation
• Added
table alias (AS p) to subquery for clarity
• Fixed potential column
reference issue in WHERE clause

+8/-7     
20250423220157_little_meadow.sql
Format stage plots update statement consistently                 

supabase/migrations/20250423220157_little_meadow.sql

• Applied 4-space indentation to UPDATE statement
• Standardized CASE
statement formatting with consistent indentation
• Improved overall
SQL formatting consistency

+8/-7     
20250630100000_wheres_cj.sql
Standardize CJ location table formatting                                 

supabase/migrations/20250630100000_wheres_cj.sql

• Applied 4-space indentation to CREATE TABLE statement
• Standardized
column definitions and constraints formatting
• Improved overall table
creation formatting consistency

+7/-7     
20250501100000_add_background_transform_to_stage_plots.sql
Format background transform update statement consistently

supabase/migrations/20250501100000_add_background_transform_to_stage_plots.sql

• Applied 4-space indentation to UPDATE statement
• Standardized SET
clause formatting with consistent indentation

+3/-3     
20250905121000_create_comms_beltpacks_table.sql
Format comms beltpacks table creation consistently             

supabase/migrations/20250905121000_create_comms_beltpacks_table.sql

• Standardized RLS policy formatting with 4-space indentation
• Added
table alias (AS p) to subquery for clarity
• Fixed potential column
reference issue in WHERE clause

+8/-7     
20250905134659_add_beltpack_channel_assignments.sql
Standardize JSONB formatting in beltpack channel assignments

supabase/migrations/20250905134659_add_beltpack_channel_assignments.sql

• Standardized JSONB default value formatting to uppercase '[]'::JSONB

• Applied consistent SQL formatting for column addition

+1/-1     
20250430110000_add_crew_key_to_schedules.sql
Standardize JSONB formatting in crew key column                   

supabase/migrations/20250430110000_add_crew_key_to_schedules.sql

• Standardized JSONB default value formatting to uppercase '[]'::JSONB

• Applied consistent SQL formatting for column addition

+1/-1     
20250430120000_add_labor_schedule_to_production_schedules.sql
Standardize JSONB formatting in labor schedule column       

supabase/migrations/20250430120000_add_labor_schedule_to_production_schedules.sql

• Standardized JSONB default value formatting to uppercase '[]'::JSONB

• Applied consistent SQL formatting for column addition

+1/-1     
20250502100000_add_detailed_schedule_to_production_schedules.sql
Standardize JSONB formatting in detailed schedule column 

supabase/migrations/20250502100000_add_detailed_schedule_to_production_schedules.sql

• Standardized JSONB default value formatting to uppercase '[]'::JSONB

• Applied consistent SQL formatting for column addition

+1/-1     
20250423203118_navy_rain.sql
Add missing newline at end of migration file                         

supabase/migrations/20250423203118_navy_rain.sql

• Added missing newline at end of file
• Applied consistent file
formatting standards

+1/-1     
20250425225230_hidden_math.sql
Add missing newline at end of migration file                         

supabase/migrations/20250425225230_hidden_math.sql

• Added missing newline at end of file
• Applied consistent file
formatting standards

+1/-1     
20250811120000_add_default_column_colors_to_run_of_shows.sql
Standardize JSONB formatting in default column colors       

supabase/migrations/20250811120000_add_default_column_colors_to_run_of_shows.sql

• Standardized JSONB default value formatting to uppercase '{}'::JSONB

• Applied consistent SQL formatting for column addition

+1/-1     
20250821192800_add_phase_flipped_to_tf_measurements.sql
Remove unnecessary quotes in ALTER TABLE statement             

supabase/migrations/20250821192800_add_phase_flipped_to_tf_measurements.sql

• Removed unnecessary quotes around table name public.tf_measurements

• Applied consistent SQL formatting for ALTER TABLE statement

+2/-2     
Configuration changes
4 files
eslint.config.js
ESLint configuration for legacy code compatibility             

eslint.config.js

• Disabled strict ESLint rules for legacy code compatibility
• Added
rules to turn off @typescript-eslint/no-explicit-any,
@typescript-eslint/no-unused-vars, react-hooks/exhaustive-deps, and
@typescript-eslint/no-empty-object-type
• Focused on allowing existing
code patterns while maintaining quality for new code

+5/-0     
ci.yml
Add comprehensive CI workflow with multi-language linting

.github/workflows/ci.yml

• Added comprehensive CI workflow for pull requests and pushes

Configured Node.js, Python, and pnpm setup with caching
• Integrated
ESLint, TypeScript, Ruff, and SQLFluff linting checks
• Added build
and test execution steps

+67/-0   
pyproject.toml
Add Ruff linting configuration for Python capture agent   

agents/capture-agent-py/pyproject.toml

• Added Ruff as development dependency for Python linting
• Configured
comprehensive Ruff linting rules and settings
• Added line length,
target version, and import sorting configuration
• Set up known
first-party packages for import organization

+31/-0   
.sqlfluff
Add SQLFluff configuration for SQL linting standards         

.sqlfluff

• Added SQLFluff configuration file for SQL linting
• Configured
PostgreSQL dialect and formatting rules
• Set lowercase capitalization
policy and line length limits
• Excluded specific rules for project
compatibility

+13/-0   
Dependencies
2 files
pnpm-lock.yaml
ESLint dependencies and package lock updates                         

pnpm-lock.yaml

• Added new ESLint-related dependencies including @eslint/js, eslint,
eslint-plugin-react-hooks, eslint-plugin-react-refresh, globals, and
typescript-eslint
• Updated dependency versions and added new
@types/node and undici-types entries
• Maintained existing dependency
structure while adding linting infrastructure

+43/-2   
package.json
Update version and add comprehensive linting configuration

package.json

• Updated version from 1.5.6 to 1.5.6.1
• Added ESLint dependencies
and configuration
• Enhanced lint-staged configuration with ESLint,
Python, and SQL linting
• Added TypeScript and globals dependencies

+13/-3   
Bug fix
6 files
20250905094431_create_comms_planner_tables.sql
SQL formatting and table reference fixes                                 

supabase/migrations/20250905094431_create_comms_planner_tables.sql

• Applied consistent SQL formatting with proper indentation
• Updated
table aliases and JOIN syntax for better clarity
• Fixed potential
column reference issue in RLS policies

+32/-28 
20250423193302_ancient_disk.sql
SQL syntax fix for patch sheets migration                               

supabase/migrations/20250423193302_ancient_disk.sql

• Added missing semicolon at the end of the SQL block
• Applied minor
formatting fix for proper SQL syntax

+1/-1     
VideoCategoryPage.tsx
Fix variable mutability in video category page                     

apps/web/src/pages/VideoCategoryPage.tsx

• Changed safeSpeeds variable declaration from let to const
• Applied
ESLint recommendation for immutable array declaration

+1/-1     
SharedShowModePage.tsx
Fix variable mutability in shared show mode page                 

apps/web/src/pages/SharedShowModePage.tsx

• Changed rowStyle variable declaration from let to const
• Applied
ESLint recommendation for immutable object declaration

+1/-1     
ShowModePage.tsx
Fix variable mutability in show mode page                               

apps/web/src/pages/ShowModePage.tsx

• Changed rowStyle variable declaration from let to const
• Applied
ESLint recommendation for immutable object declaration

+1/-1     
ChartDetailModal.tsx
Fix variable mutability in chart detail modal                       

apps/web/src/components/analyzer/ChartDetailModal.tsx

• Changed data variable declaration from let to const
• Applied ESLint
recommendation for immutable variable declaration

+1/-1     
Documentation
2 files
CHANGELOG.md
Version 1.5.6.1 changelog documentation                                   

CHANGELOG.md

• Added comprehensive changelog entry for version 1.5.6.1
• Documented
new CI/CD pipeline, pre-commit quality gates, and linting
infrastructure
• Detailed technical enhancements and legacy code
compatibility improvements

+56/-0   
CONTRIBUTING.md
Document CodeRabbit AI assistant integration and workflow

CONTRIBUTING.md

• Added detailed section about CodeRabbit AI assistant integration

Updated pull request process to emphasize automated PR descriptions

Added information about intelligent code reviews and smart suggestions

• Enhanced contributor guidelines with AI-assisted workflow details

+33/-1   
Additional files
1 files
AllRunOfShows.tsx +0/-1     

@netlify

netlify Bot commented Sep 10, 2025

Copy link
Copy Markdown

Deploy Preview for sounddocsbeta ready!

Name Link
🔨 Latest commit 3d1b8b9
🔍 Latest deploy log https://app.netlify.com/projects/sounddocsbeta/deploys/68c175cb5ea6350008edda16
😎 Deploy Preview https://deploy-preview-83--sounddocsbeta.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 No relevant tests
🔒 Security concerns

RLS and anonymous edit access:
Multiple migrations enable anonymous UPDATE via shared links (e.g., policies allowing TO anon with link_type='edit'). Confirm this is intentional and strictly constrained by share_code flows and expirations. Also review SECURITY DEFINER functions (e.g., get_public_run_of_show_by_share_code, handle_share_access, is_valid_share_link) to ensure least-privilege, correct search_path, and no SQL injection via parameters.

⚡ Recommended focus areas for review

Possible Issue

The change in _hann_cached removes the space after the if and may have preserved logic, but other parts rely on numpy/scipy window behavior; confirm that returning ones for M<=1 is intended and that callers handle M=0/1 without division by zero elsewhere.

def _hann_cached(M: int) -> np.ndarray:
    if M <= 1:
        return np.ones(max(M,1))
    n = np.arange(M)
    return 0.5 - 0.5*np.cos(2*np.pi*n/(M-1))
Resource Handling

In audio_callback, pooled buffer handling was adjusted; ensure all error paths still always return buffers to the pool to avoid leaks and that pool size bounds are respected under backpressure.

    nonlocal pool_miss_count
    if status:
        print(f"Audio callback status: {status}")

    buf = None
    try:
        buf = pool.popleft()
        # PortAudio reuses its buffers; copy into our reusable buffer
        np.copyto(buf, indata, casting='no')
    except IndexError:
        # pool exhausted - track misses
        pool_miss_count += 1
        # Create new buffer only if under max size
        if len(pool) < max_pool_size:
            buf = indata.copy() if indata.dtype == np.float32 else indata.astype(np.float32, copy=True)
        else:
            # Pool at max, drop this frame to prevent unbounded growth
            return

    try:
        loop.call_soon_threadsafe(aq.put_nowait, buf)
    except Exception:
        # queue full -> drop; always return buffer to pool
        if buf is not None:
            try:
                pool.append(buf)
            except Exception:
                pass

stream = None
try:
    fs = int(config.sampleRate)
    nperseg = int(config.nfft)
    max_delay_ms = int(getattr(config, "maxDelayMs", 300))
    max_lag_samples = int(np.ceil(fs * max_delay_ms / 1000.0))

    buffer_len = nperseg + 2*max_lag_samples + int(0.75*nperseg)
    noverlap = int(0.75 * nperseg)
    hop_size = nperseg - noverlap

    analysis_buffer = np.zeros((buffer_len, num_channels), dtype=np.float32)
    carry = 0  # how many new samples since last analysis
    last_send = 0.0
    target_fps = 20.0  # UI update rate
    send_interval = 1.0 / target_fps

    stream = sd.InputStream(
        device=int(config.deviceId),
        samplerate=config.sampleRate,
        blocksize=1024,               # <= smaller, smoother
        channels=num_channels,
        dtype="float32",
        callback=audio_callback,
        latency="high",               # optional: reduce overruns
    )
    stream.start()

    while True:
        # wait for at least one block
        block = await aq.get()

        # Process blocks one at a time to avoid memory spikes
        # Limit how many we drain at once
        max_drain = 4
        blocks_to_process = [block]
        drain_count = 0
        while drain_count < max_drain:
            try:
                blocks_to_process.append(aq.get_nowait())
                drain_count += 1
            except asyncio.QueueEmpty:
                break

        # roll each block into the analysis buffer without concatenating
        for b in blocks_to_process:
            Lb = b.shape[0]
            if Lb >= buffer_len:
                analysis_buffer[...] = b[-buffer_len:, :]
                carry = hop_size  # force analysis
            elif Lb > 0:
                analysis_buffer[:-Lb, :] = analysis_buffer[Lb:, :]
                analysis_buffer[-Lb:, :] = b
                carry += Lb

            # Always return buffer to pool
            if len(pool) < max_pool_size:
                try:
RLS Correctness

New UPDATE policies use JOINs and WITH CHECK; validate that table-qualified references (e.g., public.patch_sheets.id) resolve correctly in Supabase and that policies don’t unintentionally grant edits via claimed shares across resources.

ON public.patch_sheets
FOR UPDATE
TO authenticated
USING (
    (auth.uid() = user_id)
    OR EXISTS (
        SELECT 1
        FROM public.shared_links AS sl
        INNER JOIN public.user_claimed_shares AS ucs ON sl.id = ucs.shared_link_id
        WHERE
            sl.resource_id = public.patch_sheets.id
            AND sl.resource_type = 'patch_sheet'
            AND sl.link_type = 'edit' -- Critical check for edit permission
            AND ucs.user_id = auth.uid()
    )
)
WITH CHECK (
    (auth.uid() = user_id)
    OR EXISTS (
        SELECT 1
        FROM public.shared_links AS sl
        INNER JOIN public.user_claimed_shares AS ucs ON sl.id = ucs.shared_link_id
        WHERE
            sl.resource_id = public.patch_sheets.id
            AND sl.resource_type = 'patch_sheet'
            AND sl.link_type = 'edit'
            AND ucs.user_id = auth.uid()
    )
);

-- RLS UPDATE Policy for stage_plots
CREATE POLICY "Users can update own or claimed editable stage plots"
ON public.stage_plots
FOR UPDATE
TO authenticated
USING (
    (auth.uid() = user_id)
    OR EXISTS (
        SELECT 1
        FROM public.shared_links AS sl
        INNER JOIN public.user_claimed_shares AS ucs ON sl.id = ucs.shared_link_id
        WHERE
            sl.resource_id = public.stage_plots.id
            AND sl.resource_type = 'stage_plot'
            AND sl.link_type = 'edit'
            AND ucs.user_id = auth.uid()
    )
)
WITH CHECK (
    (auth.uid() = user_id)
    OR EXISTS (
        SELECT 1
        FROM public.shared_links AS sl
        INNER JOIN public.user_claimed_shares AS ucs ON sl.id = ucs.shared_link_id
        WHERE
            sl.resource_id = public.stage_plots.id
            AND sl.resource_type = 'stage_plot'
            AND sl.link_type = 'edit'
            AND ucs.user_id = auth.uid()
    )
);

-- RLS UPDATE Policy for run_of_shows
CREATE POLICY "Users can update own or claimed editable run of shows"
ON public.run_of_shows
FOR UPDATE
TO authenticated
USING (
    (auth.uid() = user_id)
    OR EXISTS (
        SELECT 1
        FROM public.shared_links AS sl
        INNER JOIN public.user_claimed_shares AS ucs ON sl.id = ucs.shared_link_id
        WHERE
            sl.resource_id = public.run_of_shows.id
            AND sl.resource_type = 'run_of_show'
            AND sl.link_type = 'edit'
            AND ucs.user_id = auth.uid()
    )
)
WITH CHECK (
    (auth.uid() = user_id)
    OR EXISTS (
        SELECT 1
        FROM public.shared_links AS sl
        INNER JOIN public.user_claimed_shares AS ucs ON sl.id = ucs.shared_link_id
        WHERE
            sl.resource_id = public.run_of_shows.id
            AND sl.resource_type = 'run_of_show'
            AND sl.link_type = 'edit'
            AND ucs.user_id = auth.uid()
    )
);

-- RLS UPDATE Policy for production_schedules
CREATE POLICY "Users can update own or claimed editable production schedules"
ON public.production_schedules
FOR UPDATE
TO authenticated
USING (
    (auth.uid() = user_id)
    OR EXISTS (
        SELECT 1
        FROM public.shared_links AS sl
        INNER JOIN public.user_claimed_shares AS ucs ON sl.id = ucs.shared_link_id
        WHERE
            sl.resource_id = public.production_schedules.id
            AND sl.resource_type = 'production_schedule'
            AND sl.link_type = 'edit'
            AND ucs.user_id = auth.uid()
    )
)
WITH CHECK (
    (auth.uid() = user_id)
    OR EXISTS (
        SELECT 1
        FROM public.shared_links AS sl
        INNER JOIN public.user_claimed_shares AS ucs ON sl.id = ucs.shared_link_id
        WHERE
            sl.resource_id = public.production_schedules.id
            AND sl.resource_type = 'production_schedule'
            AND sl.link_type = 'edit'
            AND ucs.user_id = auth.uid()
    )
);

@qodo-code-review

qodo-code-review Bot commented Sep 10, 2025

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Python 3.11 dependency risk

The Python agent now relies on datetime.UTC and modern typing (list[T]),
implicitly requiring Python 3.11+. Verify that build/packaging (Poetry,
PyInstaller, CI runners, and user environments) enforce or bundle 3.11 to avoid
runtime failures on 3.10/3.9 machines. If 3.11 cannot be guaranteed for all
users, add a compatibility shim or pin and validate the agent’s runtime Python
version at startup.

Examples:

agents/capture-agent-py/main.py [43]
        now = datetime.datetime.now(datetime.UTC)
agents/capture-agent-py/pyproject.toml [1-16]
[tool.poetry]
name = "capture-agent"
version = "0.1.13"
description = "SoundDocs Capture Agent for multi-channel audio analysis."
authors = ["CJ Vana cj@sounddocs.org"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.11"
websockets = "^12.0"

 ... (clipped 6 lines)

Solution Walkthrough:

Before:

# In agents/capture-agent-py/pyproject.toml
[tool.poetry.dependencies]
# No python version is specified.
# Users with Python < 3.11 can install dependencies.
numpy = "^1.26.4"
...

# In agents/capture-agent-py/main.py
import datetime
def check_certificate_validity(...):
    # This will raise an AttributeError on Python < 3.11
    now = datetime.datetime.now(datetime.UTC)
    ...

After:

# In agents/capture-agent-py/pyproject.toml
[tool.poetry.dependencies]
# Enforce the required Python version.
# Poetry will now fail installation on unsupported versions.
python = ">=3.11"
numpy = "^1.26.4"
...

# In agents/capture-agent-py/main.py
import datetime
def check_certificate_validity(...):
    # This code is now safe because the environment is guaranteed
    # to be Python 3.11+
    now = datetime.datetime.now(datetime.UTC)
    ...
Suggestion importance[1-10]: 10

__

Why: This suggestion correctly identifies a critical runtime risk, as the code now uses datetime.UTC (Python 3.11+) without enforcing this version in pyproject.toml, which could cause crashes for users on older Python versions.

High
Possible issue
Keep WebSocket server running

The server exits immediately after printing because the context manager returns
once no await keeps it alive. Await an indefinite Future to keep the server
running until cancelled. This prevents the process from exiting right after
startup.

agents/capture-agent-py/capture_agent/server.py [302-306]

 async with websockets.serve(
     handler, host, port, ssl=ssl_context,
     max_size=8*1024*1024, max_queue=2, compression=None
 ):
     print(f"Secure WebSocket server started at wss://{host}:{port}")
+    await asyncio.Future()  # run forever until cancelled
  • Apply / Chat
Suggestion importance[1-10]: 10

__

Why: This suggestion correctly identifies a critical bug where the server would exit immediately after starting, and it provides the standard correct fix to keep it running.

High
Restore UTC compatibility pre-3.11

Using datetime.UTC requires Python 3.11+. If the agent runs on 3.10 or older,
this will crash. Fall back to datetime.timezone.utc when datetime.UTC is
unavailable to keep compatibility.

agents/capture-agent-py/main.py [43-52]

-now = datetime.datetime.now(datetime.UTC)
+tz_utc = getattr(datetime, "UTC", datetime.timezone.utc)
+now = datetime.datetime.now(tz_utc)
 ...
-not_valid_after = cert_obj.not_valid_after.replace(tzinfo=datetime.UTC)
-not_valid_before = cert_obj.not_valid_before.replace(tzinfo=datetime.UTC)
+not_valid_after = cert_obj.not_valid_after.replace(tzinfo=tz_utc)
+not_valid_before = cert_obj.not_valid_before.replace(tzinfo=tz_utc)

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: This is a critical compatibility fix, as the PR's use of datetime.UTC would cause a crash on Python versions older than 3.11, which the agent might run on.

High
Fix broken RLS plan reference

The WHERE clause incorrectly compares p.id to p.plan_id, which will never match
and breaks the RLS policy. Compare the plan's id to the row's plan_id column
instead. This same issue appears in similar policies; align them to reference
the target table's plan_id.

supabase/migrations/20250905094431_create_comms_planner_tables.sql [38-47]

 CREATE POLICY "Allow access to comms_transceivers for plan owners" ON comms_transceivers FOR ALL USING (
-    auth.uid() IS NOT null
+    auth.uid() IS NOT NULL
     AND EXISTS (
         SELECT 1
         FROM comms_plans AS p
         WHERE
-            p.id = p.plan_id
+            p.id = plan_id
             AND p.user_id = auth.uid()
     )
 );

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical bug in the RLS policy where p.id = p.plan_id would always fail, breaking access control.

High
Correct RLS plan_id comparison

The RLS policy compares p.id to p.plan_id, which is invalid and will deny all
access. Update it to compare p.id with the comms_beltpacks row's plan_id. Ensure
NULL capitalization consistency.

supabase/migrations/20250905121000_create_comms_beltpacks_table.sql [13-22]

 CREATE POLICY "Allow access to comms_beltpacks for plan owners" ON comms_beltpacks FOR ALL USING (
     auth.uid() IS NOT NULL
     AND EXISTS (
         SELECT 1
         FROM comms_plans AS p
         WHERE
-            p.id = p.plan_id
+            p.id = plan_id
             AND p.user_id = auth.uid()
     )
 );

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical bug in the RLS policy where p.id = p.plan_id would always fail, breaking access control.

High
Fix invalid policy join condition

The policy again compares p.id to p.plan_id rather than the target table row's
plan_id, effectively blocking all access. Align it to p.id = plan_id to
correctly authorize owners of the plan.

supabase/migrations/20250905123341_add_foreign_key_beltpacks_to_transceivers.sql [11-20]

 CREATE POLICY "Allow access to comms_beltpacks for plan owners" ON comms_beltpacks FOR ALL USING (
     auth.uid() IS NOT NULL
     AND EXISTS (
         SELECT 1
         FROM comms_plans AS p
         WHERE
-            p.id = p.plan_id
+            p.id = plan_id
             AND p.user_id = auth.uid()
     )
 );

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical bug in the RLS policy where p.id = p.plan_id would always fail, breaking access control.

High
General
Preserve preallocated buffer usage

You pre-allocate a work array for ir but then reassign it to a new array from
irfft, losing the memory reuse and increasing allocations. Write the irfft
result into the pre-allocated buffer to avoid unnecessary allocations and
potential memory pressure.

agents/capture-agent-py/capture_agent/dsp.py [570-571]

-ir = np.fft.irfft(H_ir, n=n_ir)
+ir[:] = np.fft.irfft(H_ir, n=n_ir)
 ir_plot = np.roll(ir, n_ir // 2)
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that reassigning ir negates the benefit of pre-allocating the array, and the proposed fix correctly uses an in-place update to improve memory efficiency.

Medium
  • Update

@cj-vana cj-vana closed this Sep 10, 2025
@cj-vana cj-vana deleted the cj-prs branch September 10, 2025 13:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant