Open Questions [TEAM_WHY_NEEDED] & Tech Debt
Use this board during engineering/product reviews to record the historical “Why?” behind non-obvious rules and track cleanup priorities.
A. Consolidated [TEAM_WHY_NEEDED] Questions (29 Actionable Team Decisions)
- Env Var Split (
SUPABASE_*vsENERGY_SUPABASE_*): Why do 38 Edge Functions readENERGY_SUPABASE_URL/ENERGY_SUPABASE_SERVICE_ROLE_KEYwhile 21 functions +_shared/auth.ts::validateAuthreadSUPABASE_URL/SUPABASE_SERVICE_ROLE_KEY(andrun-schedulerrequires both)? Are they aliases to one project or a split project topology? - Global Maintenance Table Write Policy (
20240101000000:45-67): Why can any tenant company’sadmin/ownermodify globalapp_modulesandapp_modules_maintenancefor all tenants instead of restricting toplatform_operators? - DNS Verification Worker (
20261022000000): Where is the DNS TXT verification worker forwhitelisted_domainsimplemented? - Global
user_overridesScoping (20261116100000,20261116150000):user_overrideshas nocompany_idcolumn, leaking overrides across companies for multi-company users. Is a migration addingcompany_idplanned? - Non-Decrementing AI Token Add-On (
20261102120000): Why doesuser_token_quotas.purchased_token_addonpersist across every monthly reset instead of decrementing as a one-time top-up? - Missing 30-Day GDPR Purge Cron (
send-account-deletion-notice): Where is the cron job that encrypts/permanently deletes accounts 30 days afterdeletion_scheduled_at? - Legacy Agreements Stripe Webhook (
stripe-webhook/index.ts): Isstripe-webhook(agreements.stripe_payment_status) still active in DealFlow/production or dead code? submit-inquiryDev Redirect & Cardless Flag (submit-inquiry/index.ts:183): Why doessubmit-inquiryhardcodedev-dealflow.planovi.app/payment-success.phpand omitpayment_method_collection=if_required?- Client-Triggered Subscription Emails (
send-subscription-updated/cancelled): Why are these separate admin-only client-invoked endpoints instead of being sent server-side fromchange-plan/set-auto-renew/handle-stripe-webhook? - Cancelled License Floor (
recomputeLicenseTier): Why doescompanies.license_tierfloor at[1](Starter) even when a company has 0 active licenses? - 14-Day Grace Period Enforcement (
payment_failed_at): Where is the 14-daypast_duecutoff actually enforced (Flutter UI, RLS, or external cron)? - Parallel Telemetry Aggregation Pipelines: Why do
telemetry_hourly/telemetry_daily(Edge Functions) ANDhourly_telemetry_summaries(pg_cronSQL) coexist, and which is authoritative in PROD? - Unauthenticated Converter Preview (
ingest-telemetry/index.ts:81-135): Why does Flutter call unauthenticatedPOST ingest-telemetryinstead of queryingdevice_live_statevia RLS? - Pre-2026-10-18 Swapped Hourly Rows (
20261030090000:13): Should historical pre-Oct-18 rows inhourly_telemetry_summariesstay immutable or be swapped? - Legacy Pre-
company_idBilling/AI Functions: Arebilling-calculator,generate-monthly-invoices,generate-invoice-pdf,ai-energy-balancer, andgenerate-reportabandoned and ready for removal, or slated forcompany_idmigration? - Monthly Invoice Math & VAT (
generate-monthly-invoices): Why does the code double-apply0.8, charge pure consumers0 PLNin Scenario A, clamp export credits to0 PLN, and omit VAT/OSD fees despite"FAKTURA VAT"? - Invoice Email RBAC & Reply-To (
send-invoice-email): Should it gate on RBACledger.invoices|UPDATEinstead of hardcodedadmin/owner, and pass the already-queriedcompanies.contact_emailasreplyTo? - Orphaned OCR Approval Pipeline (
approve-declaration-schema): Isapprove-declaration-schema(andocr_extraction_sessions/ocr_extracted_fields) dead code now thatprocess-declaration-ocrwrites directly todeclaration_fields? get-company-declaration-schemaUsage: Why does it return all active fields across all templates (includingadminfields) without template filtering or steps? Is any client still calling it?- Hardcoded Planovi Theme in Form Links (
_shared/form_link.ts): Why docreate-form-preview,create-admin-edit-link, andissueFormLinkhardcode#32CA42/#09090Binstead of loading cooperative Zone 2 custom colors? docx-to-htmlProduction Status: Isdocx-to-html(unscopedvalidateAuth,mammoth@1.6.0, mojibake headings) still used?- Step-Apply RBAC Gap (
apply_declaration_steps): Why dodeclaration_stepsRLS andapply_declaration_stepsrequireplanovi_is_adminwhilesuggest-declaration-stepspermitsteam_declarations|OTHERS? - Gemini XML-Patching vs
Docxtemplater(submit-member-declaration): Why doessubmit-member-declarationstill usemammoth+gemini-2.5-flash+ raw XML regex instead ofgenerate-prefilled-docx/_shared/docx.ts? - Premature
is_energy_coop_member = true& GlobalADMIN_NOTIFICATION_EMAIL(submit-member-declaration): Why isis_energy_coop_memberset before board approval (unlikesubmit_on_behalf), and why is admin notification a single global env var instead of per-company admins? - Client-Orchestrated Review/Rejection Split: Why are
review-member-declaration,send-rejection-notice, andonboarding_sessionstransitions split across separate client calls instead of one atomic endpoint? - CRM
webhook_deliveriesConsumer: What service polls and deliverswebhook_deliveries(consumer_type = "crm")? - Hardcoded Placeholder Seller & Non-Expiring Signing Tokens (
generate-agreement,generate-offer,signing-api): Why are"Planowi sp. z o.o. / NIP: 000-000-00-00"hardcoded, and should signing tokens carry an expiration/enforcesigning_deadline? - Cron Wiring & Prototype Status (
run-scheduler,reminder-scheduler,tender-cron,send-event-invitation): Isrun-schedulersuperseded bypg_cron? Where arereminder-scheduler/tender-cronscheduled? Istender-cron(expired May–June 2026 mock data) an abandoned prototype? Why doessend-event-invitationgate onteam_declarations|OTHERSand omit an unsubscribe footer? - Jarvis Architecture (
jarvis/index.ts): Why does TTS upload to publicclient_files/jarvis_audio/(untracked by storage quotas, no company prefix, hardcoded Rachel voice), why inject the full OpenAPI schema when only 4 tables are writable, and how should multi-company users pick their active company?
B. Critical Security & Data-Integrity Bugs (Fix First)
- Unauthenticated Telemetry Injection & Preview Leak (
ingest-telemetry/index.ts:81-141): Preview mode runs withservice_roleand ZERO auth; ingestion only rejects badx-ssl-client-verifywhen the header is present (direct hits without header bypass mTLS). Also contains hardcodedDEFAULT_EDGE_TOKENat line 19. - Cross-Tenant IDOR in
generate-invoice-pdf&generate-resolution-document: Both accept any user JWT viavalidateAuth(req)and read/write arbitraryinvoice_idorcoopIdusingservice_rolewith zero tenant checks.generate-resolution-documentalso trusts client vote tallies and has Stored XSS. - RLS Bypass Regression on
get_15min_energy(20261118140000:1185): Overwrote20261117140000’sSECURITY INVOKERback toSECURITY DEFINER, re-opening cross-tenant telemetry reads. - Broken AI Token Quota Enforcement (
jarvis/index.ts:725):get_user_token_statusreturns a PostgREST array[{ allowed: false }]; checkingtokenStatus.allowed === falsealways evaluatesundefined, so HTTP429never fires. Alsojarvis/index.tsignoresapp_modules.min_plan = 2and RBAC, and trusts client-suppliedpending_actionJSON on[SYSTEM_CONFIRM](lines 210-212). - Over-Permissive
validateAuthon Global Cron/Admin Functions:run-scheduler,reminder-scheduler,tender-cron,cleanup-telemetry,process-alerts,process-tauron-csv,aggregate-hourly,aggregate-daily,billing-calculator,generate-monthly-invoices,ai-energy-balancerall accept any regular user JWT (allowUser: truedefault);refresh-live-stateandingest-telemetry-oldhave zero auth. - Member Can Write/Read Board-Only Fields (
submit-member-declaration,get-member-declaration,get-company-declaration-schema):submit-member-declarationdoes not blockfield_visibility === 'admin',calculated, oris_active === falsefields;get-*endpoints leakadminfields to plain members. - Unauthenticated Raw UUID Cancellation/Unsubscribe Tokens:
cancel-account-deletion(?token=<user_profile_id>) has no HMAC/expiry;grant-portal-access,send-rejection-notice, andsend-account-updated-noticepass?token=<user_profile_id>tounsubscribe, which always404s. - Stored HTML / MIME Header Injection in Emails: Unescaped user/DB strings in
submit-member-declaration,send-rejection-notice,grant-portal-access,send-account-deletion-notice,send-account-updated-notice,handle-stripe-webhook,reminder-scheduler, andjarvis(rawSubject:/To:without CRLF stripping or RFC 2047). - Global Maintenance Table Writable by Any Tenant Admin (
20240101000000:45-67): Any company’sadmin/ownercan put platform modules into maintenance for all tenants. - RBAC Drift Between DB and Edge Functions:
_shared/auth.ts(+ 5 inline copies),invite-team-member, andgrant-portal-accessstill bypass RBAC foradmin(vs DB owner-only bypass20261116150000) and check legacyteam_declarationsinstead of the 7 granular tab modules. DBhas_permission()(20261116160000) omitsal.granular_action IS NULL.
C. High-Impact Functional & Logic Bugs
- Double-Counting Demoted Building Counters (
20261118140000:1584-1606):set_building_main_counterdemotescounters.role = 'SUBMETER'but fails to updatelogical_points.meter_role = 'SUBMETER'. - Converter Maintenance Mode Not Synced (
20261118140000:573-585,618-621):fn_sync_edge_converter_to_convertersomitsstatus = EXCLUDED.statusonON CONFLICT (hardware_id) DO UPDATE, soMAINTENANCEconverters keep ingesting telemetry. - Broken
run-scheduler(run-scheduler/index.ts:188-195): Hardcodeshttp://host.docker.internal:54321, sendsheaders: {}(401s againstvalidateAuth), lacks row locking, and expects key-valuesystem_settingsschema conflicting withcoop_id-basedsystem_settings. - Broken Completion Tracking (
member-onboarding-status:154-175,248-279): Counts cleared/null answers as completed (answerMap.hasinstead of.get === true) and aggregates fields across ALL templates (including archived & admin-only). - 9 Files with Double-Encoded UTF-8 Mojibake: Crashes
pdf-libWinAnsi ingenerate-invoice-pdf&generate-report, breakscase 'ten miesiąc':ingenerate-report:599, breaks Polish Word heading mapping (Nagłówek 1) indocx-to-html:41-43, and writes corrupted Polish text ingenerate-resolution-document,ai-energy-balancer,reminder-scheduler,tender-cron. - Broken
refresh-live-state,aggregate-hourly,process-alerts:refresh-live-statehits PostgREST 1000-row cap (offline devices stay'online');aggregate-hourlycollapses 24h into 1 bucket with noonConflict;process-alertsfloods duplicate alerts and misses0Voutages & negative export spikes. - Broken
signing-apiOrder/Deadline/Finalize Checks (signing-api:308-398): Does not enforcesigning_order,signing_deadline,agreements.status, orsig.status === 'pending'; triggersfinalize-agreementonnobodyPendinginstead ofallSigned. - Jarvis Operational Bugs (
jarvis/index.ts): Expired>30mconfirm/reject falls through to Gemini; missinggoogleTokenwrites literal"PENDING_DOC_URL"or silently drops Google-only events; solo calendar events fail pre-flight validator (prompt omitsattendees);reminder_alertunhandled;allEventsqueried & discarded;user_idforced on all non-calendar inserts. - Subscription Email Bugs:
send-subscription-updated:139has"noreply@planowi.app"typo; bothsend-subscription-*blockrole === 'owner'(HTTP 500) and render#F1F5F9white text on#FFFFFF. -
reminder-schedulerOAuth Refresh Leak (lines 64-67): Saves newaccess_tokenwithout updatingexpires_at, forcing a Google OAuth refresh on every run. -
fetch-energy-newsWaterfall Bug (lines 178-225): HTTP 200 WAF HTML or 0 parsed items from WysokieNapiecie short-circuits to static fallback instead of trying CIRE.pl & Google News. - Storage Quota Blindspots: Offer/agreement PDFs (
documents/offers/...,documents/agreements/...) and Jarvis TTS MP3s (client_files/jarvis_audio/...) are excluded fromcompany_storage_quotas. - Hardcoded DEV Data in SQL Migrations:
20261016171900,20261024231000,20261030110000, and20261102140000embed DEV company UUIDd116b78e-5974-473b-a803-ccb199da744f, serial'ASL-EC-12332453574787', and interactive StudioSELECTqueries.
D. Dead, Legacy, Orphaned & Duplicated Code
- 9 Orphaned Jarvis Files (ZERO imports, missing security hardening):
supabase/functions/jarvis/{prompts/jarvis_system.ts, services/database_service.ts, services/llm_service.ts, services/tts_service.ts, tools/index.ts, tools/client_manager.ts, tools/document_gen.ts, tools/gmail_sender.ts, tools/google_calendar.ts}. - Legacy / Superseded Edge Functions:
ingest-telemetry-old,billing-calculator(replaced by SQLfn_calculate_billing_records),approve-declaration-schema(bypassed byprocess-declaration-ocr),generate-monthly-invoices,generate-invoice-pdf,ai-energy-balancer,generate-report,process-tauron-csv,export-csv(all broken bycoop_id/cooperatives/telemetry_logs/device_telemetryschema drift),stripe-webhook(unreferencedagreementswebhook),tender-cron(hardcoded expired 2026 mock data). - Dead Copy-Pasted Helpers: Unused
toIso/recomputeLicenseTier/syncLicensesFromSubscriptioninpreview-plan-change/index.ts:160-216; unreachableOPTIONShandlers aftervalidateAuthindocx-to-html,generate-resolution-document,reminder-scheduler; unusedallEventsquery injarvis/index.ts:582-586. - Severe Auth/Stripe/Email Code Duplication:
requireUser/requireStaff/hasRbacPermissionduplicated inline in 5 functions instead of_shared/auth.ts;canManageBilling/buildPlan/syncLicensesFromSubscription/stripe()duplicated across 6 billing functions. - Hardcoded
dev-URLs Across Production Code:https://dev-webpage.planovi.app/assets/logo-white.pngin all email templates,https://dev-dealflow.planovi.app/payment-success.phpinsubmit-inquiry,https://dev-panel.planovi.appdefault in 4 functions. - Severe Documentation Drift (
README.md&docs/): Embedded Astro Starlight docs (docs/) andREADME.mdare severely outdated (claim 35 functions instead of 65, describe non-existentjob_queue/coop_news_feed/QR-code VAT invoices/LLM news cron/30-day retention/253V alert threshold/non-existent.env.example&deno testsuite). Treat this blueprint—notdocs/orREADME.md—as the verified source of truth.