Latest updates and additions 10202026

This commit is contained in:
Rufus King 2026-10-20 11:39:55 -04:00
parent 80dc04a679
commit c60719845c
13 changed files with 4364 additions and 604 deletions

View file

@ -0,0 +1,64 @@
# CutTheCard Accessibility Standards (project file)
Last Updated: 2026-10-11
**Standing rule — applies to every human and every AI that touches this project:** nothing ships to QA or Production unless it meets **WCAG 2.2 Level AA**. This is a release requirement, not a polish item. When asked to build any page, modal, form, email, blog template or export, build it to this document by default without being asked.
Why this standard: WCAG 2.x AA is the benchmark courts, the U.S. DOJ (ADA Titles II/III), Section 508, and state laws (e.g. California Unruh Act, New York, Florida) use in practice. No automated tool or document can *guarantee* legal compliance; this file defines our engineering standard and evidence trail. Legal questions go to counsel.
## 1. What is built in (do not undo)
| Piece | File | Purpose |
|---|---|---|
| Accessibility stylesheet | `static/a11y.css` | Focus rings, skip link, 24px targets, reduced motion, forced-colours, 320px reflow, link underlines |
| Runtime layer | `static/a11y.js` | Skip link, `<main>`, names for controls, keyboard access for click handlers, dialog focus trap/Esc/restore, live regions, table headers, new-tab notice, `deA11y.announce()` |
| Design tokens | `shared.css` `:root` blocks | Every text token is >= 4.5:1 on every surface in BOTH themes |
| Statement page | `static/accessibility.html` | Public statement + feedback route; linked from every footer and the sitemap |
| Blog gate | `blog_sanitize.accessibility_problems()` | Publishing/scheduling is refused if an image lacks `alt`, a link is empty/vague, headings skip, or a table lacks `<th>` |
| Audit tool | `a11y/a11y_audit.py` | axe-core + 320px reflow + focus-visible + source lint; run before every Deploy to Prod |
**Every new HTML page MUST include, in `<head>`:** `<link rel="stylesheet" href="/dashboard/a11y.css?v=1" />` and `<script defer src="/dashboard/a11y.js?v=1"></script>`, plus `<html lang="en">`, a unique `<title>`, and `<meta name="viewport" content="width=device-width, initial-scale=1.0" />` (never `user-scalable=no`). Server-rendered HTML (e.g. `routers/blog.py`, email) follows the same rules.
## 2. Build rules (the checklist)
1. **Structure:** one `<h1>`; headings never skip levels; one `<main id="main-content" tabindex="-1">`; header/nav/footer outside `<main>`; every `<nav>` has `aria-label`.
2. **Colour:** use tokens (`var(--text-muted)` etc.), never raw hex for text. New text/background pairs must be >= 4.5:1 (3:1 for 18px+ bold/24px+ and UI borders/icons). Never use `opacity` to dim text. White text on `--link` blue fails: use `#2563b8`.
3. **Not colour alone:** status needs text or an icon with a text name; in-text links stay underlined.
4. **Controls:** use real `<button>` / `<a href>`. Never `onclick` on `div`/`span`/`a` without href. Min target 24x24 CSS px. Icon-only buttons need `aria-label`.
5. **Forms:** every input has a visible `<label for>`; placeholder is a hint, never the label. Use `autocomplete` tokens for name/email/password. Errors: text next to the field, `aria-invalid="true"` (use `deSetFieldError`), message in an element with `role="alert"` or `aria-live`. Say how to fix it.
6. **Dialogs:** use the existing overlay/backdrop classes (`.modal-backdrop`, `.modal-overlay`, `.auth-overlay`, ids ending `Overlay`/`Backdrop`) with an `<h2>` title and a Close/Cancel button — `a11y.js` then supplies `role="dialog"`, focus trap, Esc, and focus return. Never open a dialog without a heading.
7. **Images/charts:** informative image = real `alt`; decorative = `alt=""`. Any chart/graph needs a text or table equivalent of the data. Animated content that auto-plays > 5 s needs a pause control and must respect `prefers-reduced-motion`.
8. **Tables:** `<th scope>` headers, `<caption>` or `aria-label`; no layout tables.
9. **Dynamic updates:** announce results/toasts with `deA11y.announce('Saved', 'polite')`.
10. **Keyboard:** everything reachable and operable with Tab/Enter/Space/Esc; focus order matches reading order; focus never hidden by sticky UI; no keyboard traps.
11. **Reflow/zoom:** no horizontal scrolling at 320px wide (400% zoom); do not set fixed widths on content containers.
12. **Time limits / auth:** no CAPTCHA or cognitive-test login; password fields allow paste and password managers; warn before any session timeout.
13. **Language:** plain wording; consistent navigation/labels across pages.
14. **Documents we generate** (Records Archive .xlsx/.docx, emails): real headings/header rows, document title set, alt text on images, meaningful link text, language set, no information in colour alone.
15. **Blog/content authors:** descriptive alt text; descriptive link text (not "click here"); heading levels in order; the publish gate enforces the mechanical parts.
### Navigation pattern (sidebar groups, added 2026-10-11)
The grouped sidebar (`server_debteliminator.md` §8b) follows the **disclosure pattern**, not a menu/tab widget: each group header is a real `<button type="button">` with `aria-expanded` and `aria-controls` pointing at a `<ul>` panel (hidden with the `hidden` attribute when closed); child links are normal `<a>`s in `<li>`s; the current page's link has `aria-current="page"`. Top-level icons are inline SVG with `aria-hidden="true"`; in the collapsed rail the text labels stay in the DOM (visually clipped) so names are never lost. New nav entries must be added to `DE_NAV_ALL` / `DE_NAV_ADMIN` in `shared.js` - never hand-written per page. Do not use `role="menu"`/`menuitem` here, and do not put `role="group"` on a `<ul>` (axe fails it).
## 3. Release gate (every deploy)
1. `python3 a11y/a11y_audit.py --app <qa app dir> --fail-on serious` → must print **PASS** (both themes).
2. Manual 5-minute pass on every NEW or CHANGED screen: (a) unplug the mouse — complete the task with keyboard only, focus always visible; (b) 200% and 400% zoom — nothing lost; (c) VoiceOver (Mac/iOS) or NVDA (Windows) — headings, form labels and errors are read sensibly; (d) light AND dark theme.
3. DevLog task notes: record "A11y audit PASS + manual pass done" before clicking Deploy to Prod.
4. `a11y.js` debug output (QA hostname, or `?a11y=1`): fix every "repaired at runtime" message in the source — the runtime layer is a safety net, not the plan.
## 4. Known gaps / open items (update as closed)
- Full manual screen-reader review of: Debt Reduction Plan timeline, Payment Register grid, Windfall/Milestones, charts.
- Records Archive .xlsx/.docx accessibility structure not yet reviewed.
- Placeholder-as-label still exists in some index/account/donate forms (named via the runtime layer; add visible labels when touching them).
- Click-only `span`/`div` controls remain in index/payoff/milestones/windfall (made keyboard operable by the runtime layer; convert to `<button>`).
- Email templates (`email_templates.py`, mailer) not yet audited.
- Grouped sidebar (2026-10-11): axe (WCAG 2.x A/AA) clean in dark + light and 320 px reflow verified in headless Chromium; **`a11y_audit.py` and the manual keyboard/screen-reader pass still to be done** on the new nav and the Household page before Deploy to Prod.
- Household page and banner (v2.1.20): not yet in the manual screen-reader review list.
- Start Here home page (Home Page Swap, 2026-10-11, `public_pages/home.html` served at `/`): headings are now `<h1>`/`<h2>`/`<h3>`, decorative emoji are `aria-hidden`, link colours use `var(--link)`; **`a11y_audit.py` and the manual keyboard/screen-reader pass (signed-in and signed-out, both themes, 320 px) still to be done before Deploy to Prod.** The audit tool should be pointed at `public_pages/` as well as `static/` if it only crawls `static/`. Sidebar footer link renamed "Start Here".
- Consider a third-party audit / VPAT and periodic re-test (at least twice a year and after major redesigns).
## 5. Summary for AI systems
- Read this file before building ANY UI. Default to the rules above without being asked.
- Include `a11y.css` + `a11y.js` in every page; keep `<main>`, labels, headings, alt text, contrast tokens.
- Do not weaken `a11y.css` / `a11y.js` or remove focus outlines to "fix a look".
- Never claim the site "is ADA compliant"; say it targets WCAG 2.2 AA and was tested as described here.
- Before Deploy to Prod: run `a11y_audit.py`; report its result.
# ✔️ End of File

View file

@ -1,5 +1,5 @@
# Token Efficiency Tips for KingDezigns / Fund Tracker Work with Claude
Last Updated: 2026-08-17
Last Updated: 2026-10-11
**Read this file first, before starting other work in this project.** It captures patterns observed across a long Fund Tracker build/deploy conversation that burned more tokens than necessary — mostly from long back-and-forth deployment troubleshooting. None of this changes what Claude can do, only how efficiently a conversation gets there.
@ -28,6 +28,14 @@ Several rounds in this project asked for one small thing, got it built and deplo
The deploy pattern for this project (SCP to a scratch directory → `sudo cp` into the OMV-managed project directory → rebuild or restart depending on what changed) is now stable and documented. A short deploy script run directly on KingDezigns001/NAS16 will do this identically every time without needing a guided chat conversation at all. Ask Claude to write that script once; use it going forward instead of a fresh guided walkthrough per deploy.
## Mandatory: every file delivery opens with the deploy commands
Efficiency never means dropping the deploy block. Whenever Claude delivers files, the reply
**starts** with the full SCP → `sudo cp` → restart command sequence in a single block (real file
names, `sudo rm` for deleted files, restart-vs-rebuild stated, a verification line or two), then
explains the change. Batching into one block is the efficient part; omitting it is never acceptable,
even on small changes and follow-up revisions. Template: `server_debteliminator.md` §3a-0.
## When reporting an error, paste full context in one message
Partial command output followed by a follow-up asking for more context costs an extra round trip every time. Pasting the full command **and** its full output together the first time (even if it looks noisy) usually resolves faster than an incremental back-and-forth.

View file

@ -0,0 +1,322 @@
# Debt Eliminator / CutTheCard — Subscription Model Transition Plan
Last Updated: 2026-10-11
> **Status update (2026-09-30):** the v2.1.3 production backup contains
> the SitePay code this plan describes — `routers/subscribe.py` (paid
> Checkout + Customer Portal), `subscription_reconcile.py` (daily
> reconciliation, trial-ending emails), `User.access_status`, the
> `billing-locked.html` lockout page, `subscribe.html`, admin endpoints for
> reconciliation / donor migration / settings, and the Admin → Subscriptions
> page. Individual phase checkboxes below have **not** been re-verified
> against source. Also new: subscription payments are now recorded in the
> `donations` ledger with `payment_kind="subscription"` and surfaced on
> Admin → Subscriptions (tiles, per-user amounts, year selector) and the new
> Admin → Revenue page — see `server_debteliminator.md` §12g (this departs
> from Phase 3's original "writes no Donation row" wording for invoices).
>
> **Note (2026-10-11):** v2.1.20 added **Household Sharing**
> (`server_debteliminator.md` §12j). Per the Help Center text, *sharing your
> accounts is part of a paid plan; opening a household you were invited to is
> not limited* - so `access_status` interacts with household features (an
> owner whose access lapses should lose the ability to share; a member's
> own access is independent). Enforcement details were not verified against
> source. The QA compose file in the v2.1.20 backup now contains a
> `STRIPE_SECRET_KEY` entry, so the "QA has no Stripe keys" blocker listed in
> Phase 1 may be resolved - confirm test-mode keys and a separate QA webhook.
>
> **Original status: Planning — not yet built.** This document defines the target
> architecture and phased build plan for converting CutTheCard from a
> donation-supported free tool to a free-trial → paid-subscription model,
> with Stripe remaining the payment processor. Nothing in this document is
> live yet. Once Phase 1 work begins, treat `server_debteliminator.md` as
> authoritative for what has actually shipped, and this file as the plan
> being executed against — update this file's checkboxes/status as phases
> complete rather than letting it silently go stale.
>
> This document should be linked from `network_index.md` alongside the
> other `server_debteliminator.md`-adjacent docs once added to the project.
---
## 0. Why This Document Exists
CutTheCard currently supports itself via optional one-time and recurring
Stripe donations (see `server_debteliminator.md` §12a). This plan covers
converting to: free trial for new signups, a paid monthly subscription
after the trial, permanent free access for admin accounts, and an
admin-controlled mechanism to grant free access (forever or until a date)
to specific users. Stripe remains the payment processor — this is a
billing-model change, not a payment-processor change.
---
## 1. Business Model Decisions (confirmed)
| Decision | Value |
|---|---|
| Admin accounts (including the primary admin) | Never pay, always full access — no Stripe involvement |
| Admin-grantable free access | Forever, or until a specific date — admin-set, audit-logged |
| New-signup trial | **60 days, no credit card required at signup** (see §2) |
| Existing **one-time** donors | Granted **4 months of free access** as a thank-you, starting at paywall launch |
| Existing **recurring/monthly** donors | **Auto-converted to subscriber status** — their existing Stripe subscription continues uninterrupted; this is not a new checkout |
| Payment processor | Stripe (unchanged) |
| Pricing / plan tiers | Not yet set — single plan assumed for launch; multi-tier is explicitly out of scope until there's demand (see Phase 5) |
**Open item to confirm before Phase 4:** anonymous one-time donations
(`Donation.user_id IS NULL`) have no account to grant free access to.
Decide whether to (a) leave as-is — no account, nothing to grant, or
(b) email anonymous donors with a matching donor_email inviting them to
create/link an account to claim their 4 free months. Recommend (a) for
launch simplicity, with (b) as a possible Phase 5 follow-up.
---
## 2. Trial Length — 60 Days, and Why
CutTheCard's value doesn't show up on day one — the debt-free date
visibly moving, a balance-transfer opportunity appearing, the plan
re-ranking after a real payment lands, all take at least one full billing
cycle to happen. A 30-day trial mostly captures people before the product
has done anything for them.
**Decision: 60-day trial, no card required at signup.** Rationale:
- Covers two monthly cycles for nearly every user — enough to see at
least one "the plan updated because you made a payment" moment.
- No card at signup means zero billing risk during the trial — nothing
to auto-charge, nothing to fail — which also keeps "trial expired" and
"payment failed" as two separate, simpler code paths at launch instead
of one tangled one.
- The admin free-access grant is the escape valve for the "this
particular person needs month 3" case, so the trial length doesn't need
to be solved perfectly up front — an admin can just extend someone
manually after a support conversation.
- Instrumented from Phase 1 (see below) so the number can be revisited
with real data in Phase 5, rather than guessed a second time.
**Trial length must be admin-configurable** via `SystemSetting` (same
pattern as `donation_enabled`/`default_theme`), not hardcoded — so it can
be tuned later without a deploy.
---
## 3. Target Data Model
### `users` — new columns
| Column | Purpose |
|---|---|
| `trial_ends_at` | Set at registration from the `SystemSetting` trial-length value |
| `free_access_forever` | Bool — admin grant, never expires |
| `free_access_until` | Nullable date — admin grant, expires on this date |
| `free_access_granted_by` | Username of the granting admin (or `"system-migration"` for the donor grandfather, §6) |
| `free_access_reason` | Free text, shown in Admin UI |
| `stripe_customer_id` | Stripe Customer, distinct from any anonymous donation's customer record |
| `stripe_subscription_id` | Stripe Subscription |
| `subscription_status` | Mirrors Stripe's `status` (`trialing`/`active`/`past_due`/`canceled`/`unpaid`) — written **only** by webhook handlers or the reconciliation job, never directly |
| `subscription_current_period_end` | Mirrors Stripe |
| `subscription_cancel_at_period_end` | Mirrors Stripe |
### New table — `processed_stripe_events`
`stripe_event_id` (unique), `processed_at`. Every webhook handler checks
this first and skips if already present — Stripe redelivers events, and
none of the handlers below are safe to run twice without this.
### Computed, not stored — `access_status`
A property/function, evaluated at request time from the columns above and
`is_admin`/`is_primary_admin`, in this priority order:
```
is_admin or is_primary_admin → "admin" (always full access)
free_access_forever → "free_grant"
free_access_until >= today → "free_grant"
trial_ends_at >= today → "trial"
subscription_status in → "subscriber"
(active, trialing)
subscription_status == past_due → "grace" (full access + banner)
AND within grace window
otherwise → "expired"
```
Computing this rather than storing it means it can never drift out of
sync with its inputs — the same reasoning already applied to
`is_primary_admin` being a property, not a column.
---
## 4. Phase 1 — Billing Infrastructure (invisible to users)
Nothing user-facing changes. Goal: the plumbing exists and is proven in
QA before anything can lock a real user out.
- [ ] Migration: add the `users` columns above (§3)
- [ ] Migration: create `processed_stripe_events`
- [ ] New webhook handlers in `routers/donate.py` (or a new
`routers/subscriptions.py`, TBD at build time):
`customer.subscription.updated`, `invoice.payment_failed` —
alongside the existing `checkout.session.completed`,
`invoice.paid`, `customer.subscription.deleted`
- [ ] Idempotency: every handler checks/writes `processed_stripe_events`
first
- [ ] New scheduled job: daily Stripe subscription reconciliation
(same cadence/pattern as the weekly overdue-item digest in
`devlog.py`) — pages Stripe, corrects any local
`subscription_status` drift
- [ ] Instrumentation fields/log for `first_debt_account_created_at` and
`first_payment_logged_at` per user — this is what makes the Phase 5
trial-length review possible
- [ ] **QA gets its own Stripe test-mode keys and its own webhook
endpoint.** Currently only Production has Stripe configured at all
(`server_debteliminator.md` §5) — this must exist before any of the
above can be tested.
**Exit criteria:** in QA, create a test subscription, fail a payment,
cancel it, and confirm local `subscription_status` tracks Stripe's real
state — both via webhook delivery, and via the reconciliation job alone
with webhook delivery disabled.
---
## 5. Phase 2 — Access-Status Logic and Enforcement
Still mostly invisible — this is where lockout becomes *possible*, but is
not turned on for any real user yet.
- [ ] Implement `access_status` (§3) as a computed property
- [ ] New dependency `require_active_access`, modeled directly on the
existing `require_not_suspended` (`routers/auth.py`) — applied to
the same core routers: Accounts, Transactions, Payment Register,
Debt Reduction Plan, Records Archive
- [ ] Lockout page (redirect target for `expired`) and a non-blocking
banner for the `grace`/`past_due` state
- [ ] Admin endpoint `POST /admin/accounts/{username}/grant-free-access`
— `forever: bool` or `until: date`, plus `reason` — audit-logged
the same way as other admin account actions
- [ ] Decide final grace-period length for `past_due` (recommend
matching however long Stripe's Smart Retries run, so a user is
never locked out mid-retry-cycle)
**Exit criteria:** a QA test user can be walked trial → expired → locked,
and separately admin / free-grant / subscriber → never locked, with no
ambiguity in the access-status logic.
---
## 6. Phase 3 — Real Subscription Checkout, Signup Flow, and Donor Migration
This is where it becomes a real product change.
- [ ] `trial_ends_at` auto-set on registration from the configurable
trial-length `SystemSetting`
- [ ] New subscription Checkout Session flow, distinct from the existing
one-time/recurring donation flow, and a pricing/upgrade page
- [ ] **Stripe Customer Portal integration** — self-service
cancel/update-card/view-invoices. Do not build this UI by hand;
use `billingPortal.Session`.
- [ ] Transactional emails (immediate `force=True`, same pattern as
password-reset — not routed through the throttled campaign system
in `routers/campaigns.py`, since these are time-sensitive to one
user): trial-ending-soon (~day 53), payment-failed,
subscription-canceled confirmation
- [ ] **Donor migration script** (run once, at cutover):
- **Recurring donors** — for every `Donation` row with `recurring=true`
and an active `stripe_subscription_id`, copy that subscription ID
onto the linked `User`, set `subscription_status` from the next
reconciliation run (do not guess it), and treat as `subscriber`.
**No new Stripe checkout — the existing subscription simply becomes
their paid access.**
- **One-time donors** — for every `Donation` row with `recurring=false`,
`status='completed'`, and a non-null `user_id`, set
`free_access_until = launch_date + 4 months`,
`free_access_granted_by = "system-migration"`,
`free_access_reason = "One-time donor — 4 months free at launch"`.
A donor with multiple qualifying one-time donations should not stack
— one 4-month grant per user, not per donation.
- **Anonymous one-time donors** — see the open item in §1.
**Exit criteria:** a brand-new QA signup can go trial → real Stripe
test-mode subscription → cancel → resubscribe end to end, with correct
emails at each step; the migration script runs cleanly against a copy of
Production data and produces the expected grant/subscriber counts.
---
## 7. Phase 4 — Legal, Admin Visibility, Launch Prep
- [ ] Terms of Use / new **Billing Terms** section: refund policy, what
cancellation actually does and when, clear auto-renewal disclosure
- [ ] Admin **Subscriptions** view — status, current period end, grant
reason, per user (extend the existing Admin → Donations page or add
a new one)
- [ ] New Support request type: billing issue
(`SUPPORT_REQUEST_TYPES` in `models.py`)
- [ ] Decide the fate of the existing donate button — likely kept as a
one-time "tip" option for trial/free users, reworded so it's not
confused with the subscription
- [ ] Communication plan to existing users about the change (the new
campaign-email infrastructure in `routers/campaigns.py` is
well-timed for this)
- [ ] Full QA dry run covering: trial expiry, payment failure + dunning
+ recovery, self-cancel via Customer Portal, admin free-grant,
admin extending a near-trial-expiry user, and both donor-migration
paths from §6
---
## 8. Phase 5 — Post-Launch (data-driven, not pre-planned)
- [ ] Revisit the 60-day trial length using the §4 instrumentation —
look specifically at conversion timing relative to
`first_payment_logged_at`
- [ ] Only build engagement-based auto-extension (e.g., extend trial for
users who've logged 2+ payment cycles but haven't converted) if the
data actually shows a meaningful cluster of month-3 converters who
would've been lost at 60 days
- [ ] Multiple pricing tiers, proration, annual billing — out of scope
until there's real demand for any of them
---
## 9. Standing Open Decisions
| Item | Status |
|---|---|
| Anonymous one-time donor grandfathering | Not decided — see §1 |
| Exact `past_due` grace-period length | Not decided — see §5 |
| Pricing (monthly amount) | Not yet set |
| Whether the donate button survives post-launch | Leaning yes, as a tip jar — not finalized |
---
## 10. Summary for AI Systems
- This is a **plan document, not yet built** — do not describe any of
this as live functionality until `server_debteliminator.md` reflects it.
- Target model: admin/primary-admin always free; admin can grant free
access (forever or until a date); new signups get a **60-day,
no-card-required trial**; existing **recurring** donors auto-convert to
subscribers on their existing Stripe subscription (no new checkout);
existing **one-time** donors get **4 months free** from launch.
- Access is governed by a single **computed** `access_status` property,
not a stored/cached value — priority order: admin > free_grant > trial
> subscriber > grace (past_due) > expired.
- The `require_active_access` dependency is modeled directly on the
existing `require_not_suspended` pattern — reuse the lockout mechanism
already built for self-suspension rather than inventing a new one.
- Stripe is the source of truth for subscription state — local
`subscription_status` is written only by webhook handlers and the
daily reconciliation job, never set directly. Webhook idempotency via
`processed_stripe_events` is required, since Stripe redelivers events.
- QA currently has **no Stripe keys at all** — Phase 1 cannot be tested
without adding QA-specific Stripe test-mode keys and a separate webhook
endpoint.
- Five phases: (1) billing infra, invisible; (2) access-status +
enforcement, invisible; (3) real checkout + signup flow + donor
migration, user-facing; (4) legal/admin/launch prep; (5) post-launch
data-driven tuning of the trial length.
- The 60-day trial number is a starting hypothesis, deliberately
instrumented for revision — not a final answer.
---
# ✔️ End of File

View file

@ -0,0 +1,434 @@
# OpenCode + Ollama Setup Summary
**Machine:** KingDezigns-AI-001
**Originally written:** September 14, 2026
**Last Updated:** September 19, 2026
> **What changed on 2026-09-19 (fast summary):** Ollama was upgraded from
> v0.17.5 to v0.34.2 (required to pull the `qwen3.6` models), which exposed
> a Vulkan regression on this machine's Radeon 780M, so Ollama is now
> **pinned to v0.32.9**. A duplicate context-length setting was fixed
> (effective context is now 32768, was silently 16384), KV-cache
> quantization and an iGPU-enable override were added, and a backup/restore
> script (`~/ollama-safe.sh`) was created. Kilo Code was evaluated and
> removed. Full detail in the sections below; the current known-good state
> is summarized in "Current Known-Good State."
## 🛟 Quick Reference — Backup and Rollback (read this first)
**Before ANY Ollama change (update, downgrade, config edit), take a backup:**
```bash
~/ollama-safe.sh backup # asks for sudo; takes a minute; ~3.9 GB each
~/ollama-safe.sh list # confirm the new backup appears
```
Wait for the line `Backed up Ollama v<version> to ~/ollama-backups/<timestamp>-v<version>` before changing anything.
**If something breaks, roll back to a specific backup (recommended):**
```bash
~/ollama-safe.sh list # find the directory name you want
~/ollama-safe.sh restore ~/ollama-backups/<directory-name> # restore that exact state
```
Plain `~/ollama-safe.sh restore` (no directory) restores the **newest**
backup by name — usually the state you are trying to get away from — so
always pass the directory when rolling back to an older version.
**What restore does:** stops Ollama, puts back the saved binary, the bundled
libraries (including Vulkan), the service file and all drop-in config files,
reloads systemd, restarts Ollama, and prints the version and model list.
It does **not** touch downloaded model files.
**After any restore, verify:**
```bash
ollama --version # expect the version you restored
ollama list # all models still listed
systemctl show ollama -p Environment --no-pager | tr ' ' '\n' | grep -i -E "kv_cache|context|igpu|vulkan"
ollama run gpt-oss:20b "say hi" && ollama ps # expect 100% GPU
```
**Which backup to restore:**
| Goal | Restore this |
|---|---|
| Back to the original working setup (Ollama v0.17.5, no qwen3.6 support) | `~/ollama-backups/20260918-233357-v0.17.5` |
| Back to v0.34.2 (has the Vulkan regression for large models — not recommended) | `~/ollama-backups/20260919-204850-v0.34.2` |
| Back to the current working state (v0.32.9) | `~/ollama-backups/20260919-205838-v0.32.9` |
The script lives at `~/ollama-safe.sh`. If it is ever lost, it can be
recreated; see "Backup and Restore Script" below for what it backs up.
---
## Hardware
**GMKtec NucBox K8 Plus** — Linux Mint 22.3 (Cinnamon), kernel 6.8.0-139-generic
| Component | Details |
|---|---|
| CPU/APU | AMD Ryzen 7 8845HS w/ Radeon 780M Graphics (8 cores) |
| GPU | Radeon 780M integrated (RDNA3, gfx1103) — not on AMD's official ROCm support list |
| RAM | 29.6 GB unified (shared CPU/iGPU) |
| GPU memory Ollama can actually use | **~17.1 GiB total / ~16.3 GiB available** as reported by Ollama's Vulkan discovery (`Vulkan0`, AMD Radeon 780M, RADV PHOENIX) |
| Storage | ~1 TB (NVMe, `/dev/nvme0n1p5` root, ~768 GB, ~42% used on 2026-09-19) |
The ~16.3 GiB GPU budget is the number that decides which models run fully on
the GPU. In practice: **models of roughly 15 GB or less load at 100% GPU;
models of 17 GB or more need a CPU/GPU split** (see "Model Findings").
## Original Problem
OpenCode (AI coding agent) + Ollama + `qwen3.5:9b` would generate tool calls (file creation, shell commands) but only print them as text instead of actually executing them — nothing got created on disk.
## Fixes and Build (original, 2026-09-14)
1. **Ollama pinned to v0.17.5** — a known bug in other versions causes the "tool calls print but don't execute" symptom with qwen3.5 models.
```bash
curl -fsSL https://ollama.com/install.sh | OLLAMA_VERSION=0.17.5 sh
```
**Superseded 2026-09-19 — Ollama is now pinned to v0.32.9.** See
"Ollama Version History and Current Pin." Whether the qwen3.5
tool-calling bug still exists on v0.32.9 has **not been retested yet**
(open item).
2. **GPU acceleration switched from ROCm to Vulkan** — ROCm's runner crashes on the Radeon 780M (gfx1103 unsupported). Forced Ollama onto its Vulkan backend (Mesa RADV driver) via systemd overrides in `/etc/systemd/system/ollama.service.d/` (see "Ollama systemd Configuration" for the current file set). Confirmed working via `ollama ps` showing `100% GPU`.
3. **Model** — `qwen3.5:9b` pulled and confirmed with `tools` + `thinking` capabilities. Later testing expanded to many other models (see "Model Findings").
4. **OpenCode installed** — v1.18.31 via the official install script, `~/.opencode/bin` added to PATH.
5. **Provider config** — `~/.config/opencode/opencode.json` points OpenCode at Ollama's OpenAI-compatible endpoint (`http://localhost:11434/v1`) and explicitly marks `qwen3.5:9b` as tool-capable.
6. **Global instructions** — `~/.config/opencode/AGENTS.md` sets a standing rule so the agent defaults to creating files under `/home/rufusking/Documents/workspace/projects` without being told every time.
7. **Web access** — `opencode web --port 4096` starts a local browser UI showing projects/sessions instead of just a terminal.
8. **Desktop shortcuts** — two `.desktop` launcher icons (Start/Stop OpenCode) backed by shell scripts in `~/.local/bin/`, tracking the server via a PID file so it can be toggled without a terminal.
## Network Access Change (2026-09-14)
**Goal:** reach the OpenCode web UI from another PC on the LAN, while keeping Ollama and all model inference local to this machine only.
### What changed
`~/.local/bin/opencode-start.sh` — the server launch line was updated to bind on all network interfaces instead of just loopback:
```bash
# Before
nohup opencode web --port 4096 > "$LOGFILE" 2>&1 &
# After
nohup opencode web --port 4096 --hostname 0.0.0.0 > "$LOGFILE" 2>&1 &
```
Ollama itself was **not** touched — it still listens on `127.0.0.1:11434` only (confirmed again in the v0.34.2 server config log on 2026-09-19), so the remote PC cannot call it directly. All inference stays on this machine; the remote PC only talks to the OpenCode web UI, which relays to Ollama locally.
### Firewall
```bash
sudo ufw allow 4096/tcp
sudo ufw enable
```
### Result — confirmed working
```
Local access: http://localhost:4096
Network access: http://192.168.100.50:4096
Network access: http://192.168.100.51:4096
```
Verified reachable from a second PC on the LAN.
## ⚠️ Outstanding security item
The server log shows:
```
! OPENCODE_SERVER_PASSWORD is not set; server is unsecured.
```
Anyone on the LAN who can reach `192.168.100.50:4096` can currently create files and run shell commands on this machine through the web UI — there's no login. Recommended next step: set `OPENCODE_SERVER_PASSWORD` (check `opencode web --help` / docs for the exact env var and how OpenCode expects it to be supplied) before treating this as anything beyond a trusted-home-network convenience. Do not port-forward this port to the public internet. **Still open as of 2026-09-19.**
---
## Ollama Version History and Current Pin (2026-09-19)
| Step | Version | What happened |
|---|---|---|
| Original | **v0.17.5** | Pinned on 2026-09-14 to avoid the qwen3.5 tool-call bug. Worked, but `ollama pull qwen3.6:35b-a3b` failed with a **412 "requires a newer version of Ollama"** error. |
| Upgrade | **v0.34.2** | Installed via the plain install script. Existing models were all kept (the update does not touch model files). |
| Problem 1 | v0.34.2 | First model run showed **100% CPU** — newer Ollama treats integrated GPUs as opt-in. Fixed with `OLLAMA_IGPU_ENABLE=1` (see systemd config). After that, discovery logged `library=Vulkan ... AMD Radeon 780M Graphics (RADV PHOENIX)`. |
| Problem 2 | v0.34.2 | Models of ~17 GB and larger (`qwen3-coder:30b`, `GLM-4.7-Flash`, `qwen3.6:27b`, `qwen3.6:35b-a3b`) crashed on load with `radv/amdgpu: Not enough memory for command submission` / `vk::Queue::submit: ErrorDeviceLost`, at any context size. Both `qwen3-coder:30b` and `GLM-4.7-Flash` had loaded fine on v0.17.5. Ruled out the KV-cache setting as the cause by removing it and retesting (still crashed). |
| Downgrade | **v0.32.9** | Pinned to the last version reported working in an upstream bug report (below). **All models loaded**, including the four that crashed on v0.34.2. **This is the current pin.** |
### Upstream bug reports matching this failure
- **ollama/ollama #17748** — "AMD Radeon 780M Vulkan regression in Ollama >=0.32.10": larger models fail on a 780M with the same error text; downgrading to 0.32.9 with the same hardware/model/config restores it; small models keep working on the GPU. The reporter's env vars match this machine's (Vulkan, iGPU enable, flash attention, q8_0 KV cache).
- **ollama/ollama #18272** — related report on an AMD iGPU with a very large model; says the failure appeared from v0.32.12 and suggests the newer llama.cpp Vulkan backend changed memory allocation on iGPUs.
- **ggml-org/llama.cpp #27360** — on a Radeon 680M, a change to the default iGPU model-loading path looks like a possible cause; adding `--load-mode mmap` fixed it there. **Unconfirmed upstream, and it is not known whether Ollama exposes an equivalent setting.** Watch these threads for a fix in a newer Ollama release.
### Current pin — how to install/re-install the correct version
```bash
curl -fsSL https://ollama.com/install.sh | OLLAMA_VERSION=0.32.9 sh
```
> ⚠️ **Do NOT re-run the plain `curl ... | sh` install script without the
> `OLLAMA_VERSION=0.32.9` prefix** — it installs the latest version and
> brings the Vulkan regression back. The installer also always downloads
> ROCm libraries and prints "AMD GPU ready"; that message is misleading on
> this machine (gfx1103 is unsupported by ROCm — Vulkan is what actually
> runs).
Verify after any install:
```bash
ollama --version # expect 0.32.9
ollama list # all models still present
systemctl show ollama -p Environment --no-pager | tr ' ' '\n' | grep -i -E "kv_cache|context|igpu|vulkan"
ollama run gpt-oss:20b "say hi" && ollama ps # expect 100% GPU
```
---
## Ollama systemd Configuration
Ollama runs as a systemd service. Environment settings live in drop-in files
in `/etc/systemd/system/ollama.service.d/`. Systemd applies drop-ins in
**filename order** and a later file overrides an earlier one for the same
variable.
| File | Contents |
|---|---|
| `context.conf` | `OLLAMA_CONTEXT_LENGTH=32768` |
| `vulkan.conf` | `OLLAMA_VULKAN=1`, `GGML_VK_VISIBLE_DEVICES=0`, `LD_LIBRARY_PATH=/usr/local/lib/ollama/vulkan:/usr/local/lib/ollama`, `OLLAMA_FLASH_ATTENTION=1`, `OLLAMA_KEEP_ALIVE=10m` |
| `override.conf` | `OLLAMA_IGPU_ENABLE=1` (added 2026-09-19 — required on newer Ollama, which treats iGPUs as opt-in) |
| `kvcache.conf` | `OLLAMA_KV_CACHE_TYPE=q8_0` (added 2026-09-19 — roughly halves KV-cache memory; requires flash attention, already on) |
Other facts confirmed from the server config log: Ollama listens on
`127.0.0.1:11434`; models are stored at `/usr/share/ollama/.ollama/models`;
`OLLAMA_NUM_PARALLEL` is 1.
### Duplicate context-length bug (fixed 2026-09-19)
`vulkan.conf` originally also contained `Environment="OLLAMA_CONTEXT_LENGTH=16384"`.
Because `vulkan.conf` loads after `context.conf`, the **effective context was
16384**, not 32768 — meaning all earlier model tests ran at 16K, not 32K.
Fixed by deleting that line from `vulkan.conf`:
```bash
sudo sed -i '/OLLAMA_CONTEXT_LENGTH/d' /etc/systemd/system/ollama.service.d/vulkan.conf
sudo systemctl daemon-reload && sudo systemctl restart ollama
```
Effective value is now confirmed 32768. To check any time:
```bash
systemctl show ollama -p Environment --no-pager | tr ' ' '\n' | grep -i context
```
`ollama ps` also shows the context per loaded model. Note that the OpenCode
path goes through Ollama's OpenAI-compatible endpoint, so it uses this
**global** setting — a per-request `num_ctx` override only works when calling
Ollama's native API directly (used for the tests below).
### Reading `ollama ps`
`PROCESSOR` shows the GPU/CPU split. `100% GPU` = fully on the iGPU. A split
like `15%/85% CPU/GPU` means part of the model is in system memory (slower).
Blank output right after a request means the load failed — check
`journalctl -u ollama --no-pager --since "10 minutes ago"`.
---
## Backup and Restore Script — `~/ollama-safe.sh`
Created 2026-09-19 so an Ollama update can be undone quickly. It backs up the
Ollama **binary, bundled libraries (including the Vulkan libs), systemd unit
and drop-ins, and the model list** — but **not the model files themselves**
(a version change does not touch them, and they are many GB).
```bash
~/ollama-safe.sh backup # snapshot the current state (do this BEFORE any update)
~/ollama-safe.sh list # show existing backups
~/ollama-safe.sh restore # restore the NEWEST backup (by name)
~/ollama-safe.sh restore <backup-dir> # restore a specific backup
```
- Backups go to `~/ollama-backups/<timestamp>-v<version>/`.
- Each backup is ~3.9 GB (mostly `lib.tgz`, the bundled GPU libraries) and
asks for `sudo`.
- **Gotcha:** plain `restore` uses the *newest* backup, which is usually the
state you are trying to get away from. To go back to a specific version,
pass its directory explicitly.
- The script file needed `sudo chown $USER:$USER ~/ollama-safe.sh` + `chmod +x`
after creation because it was originally created root-owned.
- It saves `manifests.tgz` only if models are in a standard location; here the
models path did not match its defaults, so that file is absent from backups
(harmless — model files are not touched by version changes).
### Existing backups (as of 2026-09-19)
| Backup directory | Contains | Use |
|---|---|---|
| `20260918-233357-v0.17.5` | Original working state | Full rollback to the original v0.17.5 setup (note: `qwen3.6` cannot be pulled/run on it) |
| `20260919-202238-v0.34.2` | v0.34.2 with context fix applied | Only needed to return to v0.34.2 |
| `20260919-204850-v0.34.2` | v0.34.2 with context fix + KV cache config | Only needed to return to v0.34.2 |
| `20260919-205838-v0.32.9` | **Current working state** — v0.32.9 with all settings (context 32768, KV cache q8_0, iGPU enable, Vulkan) | **The one to restore to if a future change breaks things** |
The two v0.34.2 backups can be deleted to reclaim ~8 GB once v0.32.9 has
proven itself (`rm -rf ~/ollama-backups/20260919-202238-v0.34.2
~/ollama-backups/20260919-204850-v0.34.2`). Keep the v0.17.5 backup as the
original known-good state until the 7-test round is finished.
To return to the original v0.17.5 setup:
```bash
~/ollama-safe.sh restore ~/ollama-backups/20260918-233357-v0.17.5
```
---
## Model Findings
### Memory rules of thumb (this machine)
- Usable GPU memory ≈ **16.3 GiB**. Weights **plus** KV cache must fit.
- Context size drives KV-cache size. With `OLLAMA_KV_CACHE_TYPE=q8_0` the
cache is roughly half the size.
- `devstral:24b` (14 GB weights) measurements on v0.34.2 to find the limit:
| KV cache | Context | Result |
|---|---|---|
| default | 8192 | 15 GB loaded, 100% GPU |
| default | 16384 | 17 GB, 5% CPU / 95% GPU |
| default | 24576 | **crash** (out of memory) |
| q8_0 | 24576 | 16 GB, 100% GPU |
| q8_0 | 32768 | 17 GB, 5% CPU / 95% GPU |
- On v0.34.2, models that don't fit crash instead of splitting gracefully.
On v0.32.9 the split works (below).
### Current results on v0.32.9 (load test, `num_ctx=16384`, prompt "say hi")
| Model | Loaded size | Processor |
|---|---|---|
| `qwen3-coder:30b` | 19 GB | 15% CPU / 85% GPU |
| `qwen3.6:35b-a3b` | 22 GB | 30% CPU / 70% GPU |
| `qwen3.6:27b` | 18 GB | 17% CPU / 83% GPU |
| `devstral:24b` | 15 GB | 100% GPU |
| `gpt-oss:20b` | 12 GB | 100% GPU |
`gpt-oss:20b` also loaded at the global 32768 context on v0.34.2 with
100% GPU. **Not yet tested on v0.32.9 at 32768 for the larger models — open
item.** The qwen3.6 and gpt-oss models return "thinking" output, so replies
take longer than raw token speed suggests.
### Original 7-test results (on v0.17.5, effective context 16384)
Only **`gpt-oss:20b`** came close to completing all 7 tests. The goal is a
model that codes reliably and completes assigned work.
| Model | Pulled | Size | Time |
|---|---|---|---|
| qwen2.5-coder:7b | Y | 4.7 GB | 0m 2.4s |
| qwen2.5-coder:14b | Y | 9.0 GB | 1m 40s |
| ministral-3:14b | Y | 9.1 GB | 1m 36s |
| gpt-oss:20b | Y | 13 GB | 0m 39.9s |
| devstral:24b | removed at the time | 14 GB | n/a |
| qwen3-coder:30b | Y | 18 GB | 1m 20s |
| GLM-4.7-Flash | Y | 19 GB | 0m 24s |
| qwen2.5-coder:32b | Y | 20 GB | ERROR |
Working theory (not proven): the `qwen2.5-coder` models are built for
fill-in-the-middle autocomplete rather than the read-file / edit-file tool
loop an agent runs, which is why they struggle in OpenCode.
### Models currently pulled
`qwen3.6:27b`, `qwen3.6:35b-a3b`, `devstral:24b`, `granite-code:20b-instruct`,
`qwen2.5-coder:32b`, `ministral-3:14b`, `GLM-4.7-Flash`, `gpt-oss:20b`,
`qwen2.5-coder:14b`, `qwen2.5-coder:7b`, `qwen2.5:7b`, `qwen3.5:27b`,
`qwen2.5:14b`, `qwen3-coder:30b`, `qwen3.5:9b`.
### Next round of testing (not yet done)
Run the 7 tests in the OpenCode web UI on v0.32.9, in this order, and record
time + pass/fail + what broke:
1. `devstral:24b` (only local coder with a published agentic benchmark — 46.8% SWE-Bench Verified per a third-party guide; 100% GPU)
2. `qwen3.6:27b`
3. `qwen3.6:35b-a3b` (MoE, ~3B active parameters — expected to tolerate the CPU spill best)
4. `gpt-oss:20b` as the baseline
5. One file-creation task with `qwen3.5:9b` to check whether the original tool-calling bug (the reason for the v0.17.5 pin) still exists on v0.32.9
---
## Kilo Code Evaluation (2026-09-19) — Tried and Removed
Kilo Code was tried as a more polished alternative to OpenCode's web UI.
Summary of what was learned (nothing from Kilo remains installed):
- Kilo's CLI is built on the OpenCode codebase, so its engine is similar.
- Installed via npm after fixing a global-install permission error by giving
npm a user-owned prefix: `npm config set prefix ~/.npm-global` with
`~/.npm-global/bin` added to PATH in `~/.bashrc`. **That npm prefix change
is still in place and is harmless** — future `npm install -g` works without sudo.
- Version 7.7.5 had **no `kilo web` command** (`kilo web` was misread as a
project folder). The only browser UI was **`kilo console`**, which is
marked deprecated ("will be removed in a future release"). The server
returned pages correctly (verified with `curl`), but the console did not
work in the browser (blank page after sign-in), so it was abandoned.
- Removed with `kilo daemon stop`, `kilo uninstall`, and
`npm uninstall -g @kilocode/cli`, then verified with `pgrep`, `which`, and
`ss` (nothing left).
- Options identified but **not tried**: running the Kilo VS Code extension
inside `code-server` (a locally hosted browser IDE), or OpenHands'
Agent Canvas. OpenCode's web UI was kept as the daily driver.
---
## Current Known-Good State (2026-09-19)
- **Ollama:** v0.32.9 (pinned — do not run the plain installer).
- **Backend:** Vulkan (RADV) on the Radeon 780M, ~16.3 GiB usable.
- **Effective settings:** context 32768, KV cache q8_0, flash attention on,
keep-alive 10 min, iGPU enabled.
- **Verified loading:** `qwen3-coder:30b`, `qwen3.6:35b-a3b`, `qwen3.6:27b`,
`devstral:24b`, `gpt-oss:20b` (at 16384 on v0.32.9).
- **Agent front end:** OpenCode v1.18.31, web UI on port 4096 (still no
server password).
- **Rollback tool:** `~/ollama-safe.sh` (see above).
## Open Items
1. Run the 7 tests on `devstral:24b`, `qwen3.6:27b`, `qwen3.6:35b-a3b` and record results (see "Next round of testing").
2. Retest `qwen3.5:9b` tool calling on v0.32.9 (the original reason for the v0.17.5 pin).
3. Verify the larger models load at the global 32768 context on v0.32.9 (only tested at 16384); lower the global context if they crash.
4. Watch ollama/ollama #17748 and #18272 for a fix before moving past v0.32.9.
5. Set `OPENCODE_SERVER_PASSWORD` for the OpenCode web UI (still unset).
6. Other project docs (`network_index.md`, `vlan1_infrastructure.md`) still describe Ollama as "pinned to v0.17.5" — update to v0.32.9 when convenient.
*(Done 2026-09-19: v0.32.9 state backed up as `20260919-205838-v0.32.9`.)*
---
## 🧠 Summary for AI Systems
- KingDezigns-AI-001 is a local AI coding workstation on VLAN 1 (192.168.100.50/.51): Ryzen 7 8845HS, Radeon 780M iGPU (Vulkan, not ROCm), ~29.6 GB unified RAM, of which ~16.3 GiB is usable by the GPU.
- **Ollama is pinned to v0.32.9** (was v0.17.5 originally; briefly v0.34.2). v0.32.10+ has a Vulkan regression on 780M-class iGPUs that crashes models above ~16 GB with `radv/amdgpu: Not enough memory for command submission` / `ErrorDeviceLost` (ollama/ollama #17748, #18272). Never run the unpinned installer: use `curl -fsSL https://ollama.com/install.sh | OLLAMA_VERSION=0.32.9 sh`.
- The installer always fetches ROCm libs and prints "AMD GPU ready" — misleading here; Vulkan is what runs.
- Config lives in `/etc/systemd/system/ollama.service.d/`: `context.conf` (32768), `vulkan.conf`, `override.conf` (`OLLAMA_IGPU_ENABLE=1`), `kvcache.conf` (`OLLAMA_KV_CACHE_TYPE=q8_0`). Drop-ins load in filename order and later files win — a duplicate `OLLAMA_CONTEXT_LENGTH=16384` in `vulkan.conf` had been silently overriding 32768 and was removed.
- `~/ollama-safe.sh backup|restore|list` snapshots/restores the Ollama binary, libs, and systemd config (not models). Plain `restore` uses the newest backup; pass a directory to target a specific one. Take a backup before any Ollama change.
- Models that fit fully on the GPU: ≤ ~15 GB (`gpt-oss:20b`, `devstral:24b`). Larger models (`qwen3-coder:30b`, `qwen3.6:27b`, `qwen3.6:35b-a3b`) run with a CPU/GPU split on v0.32.9.
- Only `gpt-oss:20b` came close to passing all 7 agent tests so far (run on v0.17.5 at effective 16K context); `devstral:24b`, `qwen3.6:27b`, `qwen3.6:35b-a3b` are the next candidates and are untested on the 7-test suite.
- OpenCode's web UI (port 4096) still has no server password; Ollama stays loopback-only. Kilo Code was trialed and removed — nothing left installed.
- Not to be confused with **KingDezigns001**, the separate VLAN 20 admin workstation.
---
# ✔️ End of File

View file

@ -1,212 +1,329 @@
# KingDezigns Network Documentation Index
Last Updated: 2026-08-19
This index provides a structured overview of all VLANs, servers, and firewall policies in the KingDezigns network.
Each section links to its own dedicated Markdown file for clarity and modularity.
Last Updated: 2026-10-11
---
This index provides a structured overview of the KingDezigns network,
including VLANs, servers, firewall/security architecture, and hosted
applications.
------------------------------------------------------------------------
# 📁 VLAN Documentation
## 🔧 Core VLANs
- [VLAN 1 — Infrastructure](vlan1_infrastructure.md)
- [VLAN 10 — Management](vlan10_management.md)
- [VLAN 1 --- Infrastructure](vlan1_infrastructure.md)
- [VLAN 10 --- Management](vlan10_management.md)
## 🧑‍💻 Trusted User VLANs
- [VLAN 20 — Trusted Devices](vlan20_trusted.md)
- [VLAN 20 --- Trusted Devices](vlan20_trusted.md)
## 🏠 Smart Home & Guest VLANs
- [VLAN 30 — IoT](vlan30_iot.md)
- [VLAN 40 — Guest](vlan40_guest.md)
- [VLAN 30 --- IoT](vlan30_iot.md)
- [VLAN 40 --- Guest](vlan40_guest.md)
## 🧪 Server & Lab VLAN
- [VLAN 50 — Lab / Servers](vlan50_lab.md)
---
- [VLAN 50 --- Lab / Servers](vlan50_lab.md)
------------------------------------------------------------------------
# 🖥️ Server Documentation
## Core Services
- [Home Assistant Server](server_homeassistant.md)
- [NAS08 — Pi-hole, Nextcloud (+ ONLYOFFICE/Collabora), Vaultwarden, STOCKPROXY](server_nas08.md)
- [NAS16 — LAMP Stack, MariaDB, Webmin, Forgejo, Fund Tracker](server_nas16.md)
- [PLEX32 — Plex Media Server + Tautulli](server_plex32.md)
- [Forgejo — Self-Hosted Git Server (hosted on NAS16)](server_forgejo.md)
- [Fund Tracker — Multi-Profile Mutual Fund/Stock Tracking (hosted on NAS16)](server_fundtracker.md)
- [Home Assistant Server](server_homeassistant.md)
- [NAS08 --- Pi-hole, Nextcloud, Office, Vaultwarden,
STOCKPROXY](server_nas08.md)
- [NAS16 --- LAMP Stack, MariaDB, Webmin, Forgejo, Fund Tracker, Debt
Eliminator, Umami](server_nas16.md)
- [PLEX32 --- Plex Media Server + Tautulli](server_plex32.md)
- [Forgejo --- Self-Hosted Git Server](server_forgejo.md)
- [Fund Tracker --- Multi-Profile Mutual Fund/Stock
Tracking](server_fundtracker.md)
- [Debt Eliminator / CutTheCard --- Personal Debt
Tracking](server_debteliminator.md)
- [CutTheCard Subscription Model --- transition plan](debteliminator_subscription_model.md)
- [Umami --- Self-Hosted Web Analytics](server_umami.md)
## AI / Development Workstations
- [KingDezigns-AI-001 --- OpenCode + Ollama Local AI Coding
Agent](kingdezigns-ai-001-summary.md)
## Network Hardware
- [UCG Gateway Max](server_ucg.md)
---
- [UCG Gateway Max](server_ucg.md)
------------------------------------------------------------------------
# 🔥 Firewall Policies
- [Firewall Policies Overview](firewall_policies.md)
- [Firewall Policies Overview](firewall_policies.md)
---
Firewall rules themselves remain documented centrally in
`firewall_policies.md`. Service documentation should describe required
connectivity but should not duplicate the authoritative firewall rule
definitions.
------------------------------------------------------------------------
# 🛡️ Security Stack
## Intrusion Prevention
- **CrowdSec** — installed on HAS as a native HA add-on
- Agent reads NPM, HA, and SSH logs via journald
- 60 active detection scenarios
- Community blocklist updates every 2 hours
- Firewall Bouncer enforces bans at nftables level
- Email alerts on every ban decision
- All LAN VLANs whitelisted — internal IPs can never be banned
- Applies automatically to every service proxied through NPM, including Forgejo and Fund Tracker — no per-service configuration needed
- See [Home Assistant Server](server_homeassistant.md) for full configuration details
## Perimeter Defense (per server)
- **Fail2Ban** — NAS16 (active), PLEX32 (active), NAS08 (recommended)
- `ignoreip` includes `192.168.150.0/24` to prevent HAS proxy IP from being banned
- Real IP forwarding configured on NAS16 (nginx + Apache) and NAS08
- **CrowdSec** --- installed on Home Assistant Server as a native HA
add-on
- Agent reads NPM, HA, and SSH logs via journald
- Community blocklist updates every 2 hours
- Firewall Bouncer enforces bans at nftables level
- All LAN VLANs are whitelisted
- Applies automatically to NPM-proxied services, including
Forgejo, Fund Tracker, and Debt Eliminator
- See `server_homeassistant.md`
## Perimeter Defense
- **Fail2Ban**
- NAS16 active
- PLEX32 active
- NAS08 recommended
- Backend proxy IPs are protected from accidental bans
- Real IP forwarding is configured on NAS16 and NAS08
## DNS-level Protection
- **Pi-hole** — NAS08 (192.168.150.35)
- Blocks ads, trackers, and malicious domains for all VLANs
- All VLANs forced to use Pi-hole via global firewall rule 20001
- **Local DNS overrides required** for any internally-hosted service accessed by its public hostname from within the LAN (e.g. `cloud.kingdezigns.com` → `192.168.150.30`), to avoid NAT hairpin failures. See `server_nas08.md` ONLYOFFICE section for a documented example and fix.
## Application-level Auth (per service, where applicable)
- **Fund Tracker** — session-cookie auth (httponly, bcrypt-hashed passwords), account lockout after 5 failed attempts, forced password change on new/seeded accounts, versioned legal-document acceptance gating. See `server_fundtracker.md`.
- **Pi-hole** --- NAS08 (`192.168.150.35`)
- Network-wide DNS filtering
- All VLANs forced to Pi-hole through the documented firewall
policy
- Local DNS overrides are required when internal clients access an
internally hosted service through its public hostname
---
## Application Authentication
### Fund Tracker
- Session-cookie authentication
- bcrypt password hashing
- Admin/user roles
- Versioned legal-document acceptance
- See `server_fundtracker.md`
### Debt Eliminator / CutTheCard
- Session-cookie authentication
- `HttpOnly`, `SameSite=Strict` cookies
- Secure cookies behind HTTPS
- bcrypt password hashing
- Five failed-login attempts → 15-minute lockout
- Disabled accounts blocked and active sessions invalidated
- Admin-managed accounts
- Versioned Terms of Use, Privacy Statement, and Affiliate Disclosure acceptance
- Self-service account suspend/unsuspend and two-step self-delete (v2.2.0)
- **Admin Roles v2** (per-permission admin access; Primary Admin + Supervisor can assign roles)
- **Household Sharing (v2.1.20):** owner invites another user by email as view/edit; members never see full account numbers, billing, profile or Budget; owner-visible activity log
- **Accessibility:** WCAG 2.2 AA is a release requirement - see `accessibility_standards.md`
- Searchable security/audit log
- AES-256-GCM account-number encryption
- Stripe-powered donations (one-time + recurring), public Support/Contact form, downloadable Records Archive export, and a public SEO/Learning Center — see `server_debteliminator.md` for detail
- **Domains — CONFIRMED (2026-09-15):** Production is now `https://www.cutthecard.net` (was `debt.kingdezigns.com`); QA is now `https://debt.qa.cutthecard.net` (was `debt.qa.kingdezigns.com`). NPM on HAS and Dreamhost DNS were both updated for both. `cutthecard.org` redirects to `cutthecard.net` at Dreamhost only, not in NPM. Both old `kingdezigns.com` hostnames are deprecated — see `server_debteliminator.md` §0a/§2a for the standing reminder to scrub remaining references
- **Blog Engine (2026-09-30):** public SEO articles at `/blog` (outside the paywall, crawlable, in `sitemap.xml`), each revision on its own URL, with Preview/Schedule/Publish/Archive/Unpublish and scheduled go-live; no new ingress, NPM or CrowdSec changes were needed
- **Admin → Revenue / Subscriptions (2026-09-30):** unified revenue ledger (`donations.payment_kind`), subscription summary tiles, per-user monthly/yearly amounts
- **Navigation regroup (2026-10-11):** sidebar is now task-based collapsible groups (Phase 1); see `server_debteliminator.md` §8b
- **Analytics loader (2026-10-02):** one `site-scripts.js` loader tag per page; Umami page-level analytics on public and app pages (admin never tracked) — see `server_debteliminator.md` §12h
- See `server_debteliminator.md`
## Web Analytics
### Umami (self-hosted)
- `https://stats.cutthecard.net` — Docker on NAS16 (`192.168.150.40:3001`), proxied by NPM on HAS, Force SSL
- Cookie-free, first-party; no data sent to third parties
- Pi-hole local DNS override `stats.cutthecard.net` → `192.168.150.30`
- Tracks CutTheCard (public + app pages, page-level only, admin excluded) and the personal kingdezigns.com site
- Chosen over Google Analytics (privacy/trust) and Plausible (ClickHouse too heavy for a Pi)
- Default login must be changed on first login
- See `server_umami.md`
------------------------------------------------------------------------
# 🌐 Network Architecture Overview
This documentation set is designed around:
The KingDezigns network is designed around:
- Clear segmentation
- Explicit inter-VLAN access
- Isolation of untrusted devices
- Preservation of Home Assistant functionality
- AI-friendly structure and formatting
- Layered security — DNS filtering, intrusion prevention, firewall enforcement
- Clear VLAN segmentation
- Explicit inter-VLAN access
- Isolation of untrusted devices
- Preservation of Home Assistant functionality
- AI-friendly documentation
- Layered security
- Single external ingress through NPM
## Security Layer Model
```
``` text
Internet
↓
UCG Max — firewall, VLAN segmentation, geo-blocking (future)
UCG Max — firewall / VLAN segmentation
↓
CrowdSec Firewall Bouncer — nftables ban enforcement
CrowdSec Firewall Bouncer — nftables enforcement
↓
NPM on HAS — single ingress, SSL termination
NPM on HAS — HTTPS termination / reverse proxy
↓
CrowdSec Agent — log analysis, attack detection
Backend Services
├── NAS08
├── NAS16
└── PLEX32
↓
Backend Services (NAS08, NAS16, PLEX32)
↓
Fail2Ban — last-line brute force protection
Fail2Ban — backend brute-force protection
↑
Pi-hole — DNS-level ad/tracker/malware blocking (all VLANs)
Pi-hole — DNS filtering
```
---
------------------------------------------------------------------------
# 🔑 SSH Key Authentication Map
SSH key authentication is configured between the following machines — no passwords required:
SSH key authentication is configured between the documented
administrative hosts and VLAN 50 servers.
| From | To | Purpose |
|------|----|---------|
| KingDezigns001 | PLEX32 (192.168.150.45) | Remote launcher script |
| KingDezigns001 | NAS08 (192.168.150.35) | Direct SSH access |
| KingDezigns001 | NAS16 (192.168.150.40) | Direct SSH access |
| PLEX32 | NAS08 (192.168.150.35) | Backup script disk stats via SSH |
Key type: ED25519.
Key type: ED25519. Keys generated per machine — not shared.
Keys are generated per machine and are not shared.
---
------------------------------------------------------------------------
# 🖥️ KingDezigns001 — Admin Workstation Tools
# 🖥️ KingDezigns001 --- Admin Workstation
KingDezigns001 is the primary Linux administrative workstation on VLAN 20 (Trusted).
KingDezigns001 is the primary Linux administrative workstation on VLAN
20.
## Remote Launcher
A menu-driven launcher script provides one-click access to run scripts on PLEX32:
It is the normal starting point for application deployments because
NAS16 has no browser.
- **Script:** `~/scripts/plex32_launcher.sh`
- **Desktop shortcut:** `~/Desktop/PLEX32-Launcher.desktop`
- **Terminal:** gnome-terminal
For Debt Eliminator:
### Menu Options
| Option | Runs on | Script |
|--------|---------|--------|
| 1) Update Check | PLEX32 | `/usr/scripts/plex32/plex32_update_check.sh` |
| 2) Health Report | PLEX32 | `/usr/scripts/plex32/plex32_health_report.sh` |
| 3) Plex32 Backup | PLEX32 | `/usr/scripts/plex32/plex32_backup.sh` |
``` text
KingDezigns001 ~/Downloads
↓
SCP → NAS16 ~/deploys/ (never /tmp)
↓
SSH → NAS16
↓
sudo cp → QA
↓
sudo docker restart (or rebuild) QA container
↓
QA testing
↓
Dev Log Deploy to Prod (automated pipeline)
↓
Production verification
```
---
**Standing rule (mandatory, every time):** any reply that delivers files for
Debt Eliminator or Fund Tracker must *open* with the full SCP → `sudo cp` →
restart command block (real file names and paths, `sudo rm` for deleted files,
restart-vs-rebuild stated, verification lines) before explaining the change.
See `server_debteliminator.md` §3a-0 for the template.
------------------------------------------------------------------------
# 🤖 KingDezigns-AI-001 --- Local AI Coding Workstation
**Not to be confused with KingDezigns001 above** — similar name, different
machine, different VLAN.
KingDezigns-AI-001 is a **GMKtec NucBox K8 Plus** (AMD Ryzen 7 8845HS,
Radeon 780M iGPU, ~29.6GB unified RAM, Linux Mint 22.3) running
**Ollama** (local LLM inference) and **OpenCode** (an AI coding agent),
so coding-agent work can run entirely on local hardware rather than a
cloud API. Static IP reservations: **192.168.100.50** and
**192.168.100.51** — VLAN 1 (Infrastructure).
- Ollama is pinned to **v0.32.9** (since 2026-09-19; was v0.17.5 — newer
versions ≥ 0.32.10 have a Vulkan regression on this iGPU that crashes
models above ~16 GB; the original v0.17.5 pin was for a qwen3.5
tool-calling bug, retest pending) and runs on its **Vulkan**
backend (Mesa RADV) rather than ROCm, since ROCm doesn't support this
iGPU (gfx1103).
- Ollama itself listens on `127.0.0.1:11434` only — **all model
inference stays local to this machine.**
- The OpenCode web UI (`opencode web`) was opened up to the LAN
(`--hostname 0.0.0.0`, port 4096, allowed through the host's `ufw`) so
it can be reached from other VLAN 1/20 devices, while Ollama itself
remains loopback-only — remote devices talk to OpenCode, which relays
to Ollama locally.
- **⚠️ Open security item:** as of the 2026-09-14 setup, the OpenCode
server has **no password configured**
(`OPENCODE_SERVER_PASSWORD` unset) — anyone who can reach
`192.168.100.50:4096` or `.51:4096` can create files and run shell
commands on this machine with no login. This is treated as acceptable
for a trusted home LAN for now, but **port 4096 must never be
port-forwarded to the internet**, and setting a server password is a
recommended follow-up. See `kingdezigns-ai-001-summary.md` for the
exact env var and setup detail once addressed.
Full setup detail, the Ollama/OpenCode fixes applied, and the exact
network-exposure change are in
[kingdezigns-ai-001-summary.md](kingdezigns-ai-001-summary.md).
------------------------------------------------------------------------
# 🧠 Notes for AI Systems
- **File update workflow (read this first):** When asked to "update" a project file, take the existing file, make the requested changes, and present the updated file for download — do not explain the read-only/re-upload mechanism unless something about the process itself is actually in question. The user re-uploads it to the Project themselves. No caveat, disclaimer, or explanation of Claude's file access model is needed before or after doing this — just do it.
- Each file is self-contained and structured consistently.
- Section headers follow a predictable pattern for easy parsing.
- No duplicated firewall rules — all rules live in `firewall_policies.md`.
- CrowdSec configuration lives entirely on HAS — see `server_homeassistant.md`.
- VLAN files contain:
- Purpose
- Access types
- Subnet
- Expected devices
- Security rules
- AI summary
- Plex Media Server migrated from NAS08 to PLEX32 (dedicated Dell Wyse 5070) on 2026-06-18 — see `server_plex32.md`.
- PLEX32 now runs Plex + Tautulli with Intel Quick Sync hardware transcoding — optimized 2026-06-20.
- KingDezigns001 has SSH keys to all VLAN 50 servers — passwordless access for all admin tasks.
- PLEX32 has SSH key to NAS08 — required for backup script to fetch disk stats.
- **NAS08 Nextcloud update check** runs daily at 7AM — `/usr/scripts/omv/nextcloud_update_check.sh` — emails HTML report with copy-paste `occ` commands. Never use the browser UI for Nextcloud app updates (causes Apache segfault → maintenance mode deadlock).
- **NAS08 Nextcloud update check — core-update false negative fixed (2026-07-25):** the script previously checked app updates only (`occ app:update`) and had no code path for Nextcloud core/server releases, so it silently missed a core update (34.0.1 → 34.0.2) and emailed a false "up to date" report. Fixed by adding a core check via `occ update:check`, correcting the emailed Compose commands to the real path (`/kingdezignsnas/Docker/Compose/nextcloud/`, root-only, non-default filenames requiring `-f nextcloud.yml -f compose.override.yml`), and fixing a bash quoting bug that made emailed multi-line commands unreadable. Also documented: the official Nextcloud Docker image auto-upgrades on container restart via its own entrypoint — checking version status immediately after `up -d` can race that process and show a stale version for ~30 seconds. Full detail in `server_nas08.md`.
- **NAS08 Nextcloud Office editing** uses ONLYOFFICE Document Server (free Community Edition) as of 2026-07-18. Only one Office integration app should ever be enabled at a time (exception: the Collabora trial below, run as a time-boxed disable/enable swap, never simultaneous). Requires a Pi-hole local DNS override for `cloud.kingdezigns.com`, `ALLOW_PRIVATE_IP_ADDRESS=true` on the container, and matching JWT secrets between Nextcloud and the container. Full details and troubleshooting history in `server_nas08.md`.
- **NAS08 Collabora Online trial (2026-07-21, ongoing):** A second Office editor, Collabora Online (CODE), was deployed as a standalone Docker container (`collabora`, its own OMV Compose project "Collabora Office") for a head-to-head reliability trial against ONLYOFFICE — triggered by confirmed ONLYOFFICE bugs (conditional formatting crashing on formula cells; silent reverts to hours-old document versions). Only one Office app is ever enabled in Nextcloud at a time — currently `richdocuments`/Collabora is enabled, `onlyoffice` is disabled but still installed for easy rollback. Public URL `https://collabora.kingdezigns.com/`, requires its own Pi-hole local DNS override and a WOPI allow-list (`192.168.150.35`). First real-document test succeeded with a notably fast load time. Full config, setup troubleshooting, and rollback steps in `server_nas08.md`.
- **NAS08 Collabora stock/fund price macro integration (2026-07-22, working):** The ONLYOFFICE `FUNDPRICE`/`FUNDPRICE_HIST`/`STOCKPRICE`/`STOCKTIME` custom functions were ported to Collabora as a LibreOffice Basic module (`StockFunctions.bas`), calling the same STOCKPROXY backend with no backend changes required. Two `coolwsd.xml` server-config changes were required — macro execution enabling and a `net.lok_allow` hostname allowlist entry for `stocks.kingdezigns.com` — plus a fix to the previously non-functional `stocks.kingdezigns.com` Pi-hole DNS override. Confirmed working with a live price pull as of 2026-07-22. Full troubleshooting detail, exact config edits, and remaining follow-up items (recreating the full ~50-fund table, conditional-formatting re-test, recalc performance) in `server_nas08.md`.
- **NAS08 systemd-resolved DNS bug** (fixed 2026-07-18): a stray global `DNS=` override in `/etc/systemd/resolved.conf` caused duplicate/incorrect DNS answers for internal hostnames network-wide on that host. Any future "works from browser but fails from a container/script on NAS08" symptom should check `resolvectl status` for stray global DNS servers first.
- **NAS08 STOCKPROXY service (2026-07-21):** Self-hosted Flask API, Docker container `stockproxy` (`~/docker/stockproxy/`), port 5005, public URL `https://stocks.kingdezigns.com/` proxied via NPM on HAS (see Proxy Hosts table in `server_homeassistant.md`). Supplies current + historical mutual fund prices to ONLYOFFICE custom functions (`FUNDPRICE`, `FUNDPRICE_HIST`) via Yahoo Finance, scraped server-side to dodge the browser CORS block that rules out calling Yahoo directly from a spreadsheet macro. Finnhub was evaluated first but dropped from this service — confirmed no mutual fund NAV coverage on the free tier. Current-price cache: 15 min in-memory. Historical-price cache: permanent, SQLite. All endpoints require a shared-secret `key` param (Vaultwarden). Built to support the "HSA Investiments Choices" tab in `Rufus Retirement Account Tracking 2026.xlsx`. `stocks.kingdezigns.com` A record added to the daily Dreamhost DDNS refresh script. Full config and known limitations in `server_nas08.md`.
- **NAS08 RANK.EQ Err:522 circular reference fix (2026-07-23, working):** The
"HSA Investiments Choices" fund-ranking formula broke with a circular-reference error on
any sheet edit (worked fine on load) because it depended on ~50 cells fed by live
`FUNDPRICE`/`FUNDPRICE_HIST` network calls. Fixed with a button-triggered LibreOffice
Basic macro that snapshots the live price columns into static value-only columns via
`setDataArray()`, with percent-change and rank formulas rebuilt to read from the static
snapshot instead of the live columns. Full root-cause analysis and macro in
`server_nas08.md`.
- **NAS08 Collabora Finnhub removal (2026-07-23, working):** `STOCKPRICE`/`STOCKTIME`
(Finnhub-backed equity functions) errored due to a missing `net.lok_allow` entry for
Finnhub. Instead of allowlisting Finnhub, it was removed entirely — `FUNDPRICE` (STOCKPROXY)
now covers equity tickers too, and a new `FUNDTIME` function replaces `STOCKTIME`, returning
STOCKPROXY's `resolved_date` (date only, not a time-of-day timestamp — accepted tradeoff).
No `coolwsd.xml` changes required. Full detail in `server_nas08.md`.
- **Synaplan AI integration** (added 2026-07-18, not yet functional): Nextcloud connector app installed, but the required self-hosted Synaplan backend stack (PHP/MariaDB/Qdrant/optional Ollama) has not been deployed. Treat as a future project, not a bug — see `server_nas08.md` for details before troubleshooting.
- **Forgejo self-hosted Git server** (added 2026-07-26): Deployed on NAS16 (192.168.150.40) via Docker Compose — chosen over Gitea for non-profit/community governance (Codeberg e.V.). Public web UI at `https://forgejo.kingdezigns.com/` (proxied via NPM on HAS), SSH git access on port 2222 (LAN-only, no external port-forward). Provides version control with in-browser file editing/history for the `07 - Projects` folder on NAS16's share, organized as one Forgejo org per host (`NAS08`, `NAS16`, `PLEX32`) with a `<hostname>-scripts` repo in each. Data (`/opt/forgejo/data`) folded into the existing `nas16-backup.sh` job. A companion `forgejo_autosync.sh` script (not yet scheduled as of this writing) auto-commits/pushes any uncommitted changes on a timer as a safety net alongside normal manual commits. Full setup, config, and troubleshooting history in `server_forgejo.md`.
- **Fund Tracker multi-profile mutual fund/stock tracker** (added 2026-08-17): Deployed on NAS16 (192.168.150.40) via Docker Compose — FastAPI + PostgreSQL, containers `fundtracker_api`/`fundtracker_db`. Public web UI at `https://funds.kingdezigns.com/` (proxied via NPM on HAS, Force SSL). Core design: security data (ticker, price history, group classification) is shared across all profiles and synced once regardless of how many profiles track it; each profile's holdings, cost basis, and watchlist membership are private. Scoring built from quality (risk-adjusted), opportunity (quality + genuine price dip, requires both a return z-score AND a drawdown-from-high to agree), combined (harmonic mean of quality+opportunity), and rebound (peer-relative "usually near the top of its group, currently collapsed" detector, reconstructed retroactively from existing price history) scores. Market data via `yfinance` + `curl_cffi` Chrome-impersonation session — required to avoid Yahoo Finance's bot-detection blocking, and a real fix (not a sandbox artifact). Session-cookie auth (httponly, bcrypt), admin role with anonymized cross-profile Census and versioned legal-document (Terms of Use + Investment Disclaimer) publishing — a version bump immediately requires every profile to re-accept. Daily sync + personalized-per-profile email report runs via an in-process APScheduler inside the container at 06:00 UTC, **not** an OMV Scheduled Job. Full architecture, scoring methodology, deployment pattern (code-only changes = folder swap + restart; dependency changes = rebuild; compose/env changes = `up -d`; structural DB migrations require a `pg_dump` backup first), and known-issue history in `server_fundtracker.md`.
- **Fund Tracker — Portfolio/transaction tracking system documented 2026-08-19** (built in an earlier session, previously undocumented in this project): a buy-lot/sale/split register sits alongside the scoring system — FIFO/LIFO/Specific-ID sale matching, split handling that only touches lots active before the split date, a `GET /portfolio/register` endpoint, and edit/delete with lock-on-sale-allocation protection (deleting the sale restores shares and unlocks the lot). Full endpoint list, data model, and known deployment gotchas now in `server_fundtracker.md`'s dedicated Portfolio section.
- **Fund Tracker Portfolio UI — three-level collapsible register (2026-08-19):** the Portfolio page now renders **Ticker (collapsed by default) → Buy Lot → Sale(s)**, instead of showing every buy lot for every ticker at once. Frontend-only change to `portfolio.html`; deployed via scp to a `/tmp` scratch path → `sudo cp` into the root-owned `/Kingdezignsnas16/fundtracker/` project dir → `sudo docker restart fundtracker_api` (no rebuild needed for a static-file-only change, consistent with the documented code-only deployment pattern). Full detail in `server_fundtracker.md`.
- **MANDATORY — deploy commands first:** whenever you hand the user files to deploy
(tarball, patch or single file), begin the reply with the exact SCP → `sudo cp` →
`sudo docker restart <container>` block, using real file names and paths, before any
description of the change. State restart-only vs rebuild. This applies every time, to
every revision, without being asked. Template: `server_debteliminator.md` §3a-0;
Fund Tracker equivalents: `server_fundtracker.md`.
- Treat the dedicated server documentation as authoritative for
service-specific configuration.
- `firewall_policies.md` is authoritative for firewall rules.
- Do not duplicate firewall rule definitions into service files.
- When updating a project file, preserve its existing organization and
terminology unless the project itself has changed.
- Debt Eliminator / CutTheCard is hosted on NAS16.
- Branded as **CutTheCard** in all UI. As of 2026-09-15, **confirmed**:
Production is `https://www.cutthecard.net` and QA is
`https://debt.qa.cutthecard.net` — NPM on HAS and Dreamhost DNS were
both updated to match, for both environments (not just the
application's own config). `cutthecard.org` redirects to
`cutthecard.net` at Dreamhost only, not in NPM. Both
`debt.kingdezigns.com` and `debt.qa.kingdezigns.com` are deprecated;
remaining references to either across the doc set/app are tracked as
a standing reminder in `server_debteliminator.md` §0a until fully
scrubbed. See `server_debteliminator.md` §2a for detail.
- Debt Eliminator has independent QA and Production environments from launch.
- Debt Eliminator Production is port 8002.
- Debt Eliminator QA is port 8003.
- NPM on HAS is the external ingress point.
- Debt Eliminator uses PostgreSQL, FastAPI, Python 3.12, and a vanilla HTML/JS/CSS frontend.
- Debt Eliminator's transaction register uses a recompute-from-scratch ledger.
- Charge-level interest rates and promotional APR (standard + deferred) are supported per transaction.
- 0% Balance Transfer strategy evaluates donor/receiver pairs in Avalanche order; `credit_limit` field limits recommended amount.
- The Debt Reduction Plan page (formerly Payoff Strategy) has a four-step progressive layout.
- Payment Register is a year-at-a-glance application page and supports a saved Payments-Only/All-Transactions preference.
- Debt Eliminator's My Account, Admin Accounts, and Help Center pages are current application functionality.
- Debt Eliminator's DevLog supports deployment instructions, attach-to-existing-version no-version projects, an automated QA → Production deploy pipeline (`deploy_engine.py`), per-item assignment/due-date/on-hold tracking with a weekly overdue-item alert email, and a permanent deployment-history table separate from the single-generation file backup.
- **2026-09-30:** DevLog is now **v2.1.3** (app source string still 1.10.1). New since 2026-09-15: Blog Engine with revisions/archive/scheduling, unified revenue ledger + Admin → Revenue page, Subscriptions admin tiles/per-user amounts; SitePay and Email Campaigns are in the code (summary-level in `server_debteliminator.md` §0b). The latest backup is `debteliminator-v2.1.3-backup-2026-09-30_08-47-16.tar.gz`. Standing reminder still open: `APP_SECRET_KEY` unset in Production + live Stripe keys in plaintext in the compose file.
- **Earlier — since the 2026-09-03 reconciliation (DevLog v2.0.19 / app source v1.10.1 at the time):** Stripe donations (one-time + recurring), a public Support/Contact request form, self-service account suspend/delete, a Privacy Statement + Affiliate Disclosure legal document (affiliate links themselves not yet live), a downloadable Records Archive (.xlsx/.docx) export, an SEO foundation with a public six-article Learning Center, and a dark/light theme. Full detail in `server_debteliminator.md`.
- **Version namespaces must be kept separate:** the 2026-09-15 Production backup is named **v2.0.19** because that is the latest deployed DevLog version, while the application source reports **v1.10.1** and shared frontend assets are **no longer on a single cache-marker value** — split between v1.8.3 and v1.8.4 depending on the page (see `server_debteliminator.md` §4.3).
- The dedicated Debt Eliminator backup covers Production application files and the Production PostgreSQL database; it does not include the independent QA database/project tree.
- Never document actual production passwords, SMTP passwords, database passwords, encryption keys, session secrets, Stripe keys, or other credentials.
- `APP_SECRET_KEY` should be explicitly configured in QA and Production before relying on encrypted account numbers — **still open as of 2026-09-15, now higher-priority** because live Stripe secret/publishable/webhook keys were also found stored in plaintext in the Production compose file. User has acknowledged and deferred this — tracked as a standing reminder (re-surface every ~5 days) in `server_debteliminator.md` §0a/§26.
- **KingDezigns-AI-001** (added 2026-09-14) is a local AI coding workstation on VLAN 1 (192.168.100.50/.51) running Ollama + OpenCode entirely on local hardware — not to be confused with **KingDezigns001**, the separate VLAN 20 admin workstation used for Debt Eliminator/Fund Tracker deployments. Model inference (Ollama) is loopback-only; the OpenCode web UI is exposed to the LAN on port 4096 with **no server password currently set** — a known, accepted-for-now risk on the trusted home LAN, but port 4096 must never be forwarded externally. See `kingdezigns-ai-001-summary.md`.
- **Umami analytics (added 2026-10-01):** self-hosted, cookie-free web analytics on NAS16 (`stats.cutthecard.net` → NPM → `192.168.150.40:3001`; containers `umami`, `umami_db`). Secrets live in `/opt/umami/umami.secrets` via `env_file` — OMV regenerates `umami.env` and wipes manual edits, so never rely on it. CutTheCard loads tracking through a single loader, `/dashboard/site-scripts.js` (add future scripts there, not on pages). See `server_umami.md` and `server_debteliminator.md` §12h. Open: confirm custom reading events in production, add Umami to `nas16-backup.sh`, disclose analytics in the Privacy Statement, confirm default admin password changed.
---
------------------------------------------------------------------------
# 📌 Future Expansion
- **2026-10-11 (Debt Eliminator):** DevLog is **v2.1.20** (seen in a **QA** backup, `debteliminator-v2_1_20-backup-2026-10-10_23-51-34.tar.gz` - not the usual Production-only archive). New since v2.1.7: Admin Roles v2, public Demo Calculator, Milestones, Windfall Allocator, CSV/Statement Import (nothing stored), accessibility layer, reminders, Credit Utilization, Budget-to-Payoff, blog auto-archive, **Household Sharing**. Sidebar regrouped into collapsible groups (Phase 1). Details in `server_debteliminator.md` §0d, §8b, §12i-12j; accessibility rules in `accessibility_standards.md`. Standing open item: `APP_SECRET_KEY` unset (also absent from QA compose) - overdue for a reminder.
Additional files may be added for:
- **2026-10-11 (Debt Eliminator, Home Page Swap):** the old About page is now the site home page ("Start Here") at `https://www.cutthecard.net/` (and `/index.html`); the `/` → `/dashboard/` redirect was removed; Accounts remains `/dashboard/index.html`; `/dashboard/about.html` 301s to `/`; sign-in from an entry page lands on `/`. Built against the v2.1.21 QA backup; package `home-page-swap-v2.1.22.tar.gz` delivered, QA deployment not yet confirmed. Detail in `server_debteliminator.md` §0e.
------------------------------------------------------------------------
- Device inventories
- Application-specific firewall rules
- Backup and recovery procedures
- Monitoring and alerting configuration
- CrowdSec Console dashboard enrollment
- Geo-blocking configuration on UCG Max
- Authelia / forward authentication layer
- Expand remote launcher to cover NAS08 and NAS16 scripts
- **Synaplan self-hosted AI stack deployment** (PHP backend, MariaDB, Qdrant, optional Ollama) — scope resource requirements and deployment plan when ready
- **Collabora vs. ONLYOFFICE trial decision** (started 2026-07-21) — once a winner is chosen, update `server_nas08.md` and this index to reflect the final state (remove trial framing, decommission or keep the losing container, update firewall/NPM docs if the losing editor's proxy host is removed)
- **STOCKPROXY hardening** — not yet stress-tested at full ~50-ticker scale for Yahoo-side rate limiting; revisit if widespread simultaneous lookup failures are observed
- **Fund Tracker — pending feature work** (as of 2026-08-17, not yet built): self-service user account page (email update, relocated change-password), stronger primary-admin delete/demote protection, Eastern-time display throughout (currently UTC), always-visible logout control in the sidebar (currently inconsistent across pages per user report), confirmation of cookie/session behavior over the new HTTPS domain, fully-qualified-domain links everywhere (email + in-app) instead of the internal IP, public self-service signup with an admin on/off toggle and disclaimer acceptance, and open questions on geo-blocking / additional security hardening / anti-infiltration monitoring / PII collection policy. See the dedicated handoff summary provided at the end of the deployment conversation before starting this work.
- **Fund Tracker — pre-existing documentation gap fixed 2026-08-17:** the Forgejo proxy host (`192.168.150.40:3000`) was missing from `server_homeassistant.md`'s Current Proxy Hosts table despite Forgejo being deployed and documented since 2026-07-26 — added along with the new Fund Tracker entry.
- **Fund Tracker — Portfolio system testing ongoing (as of 2026-08-19):** the buy-lot/sale/split register is working but not yet exhaustively tested. Per the project's own handoff notes, remaining test cases include: purchases entered out of chronological order, sales entered against multiple lots, partial vs. complete sales, sale deletion, editing an unmatched lot, splits entered after transactions exist, reverse splits, purchases made after a historical split, lots fully sold before a split, and confirming one ticker's sales don't affect another ticker's lots. Continue from the current known-good state rather than rebuilding — see the Portfolio section of `server_fundtracker.md`.
---
# ✔️ End of Index
# ✔️ End of File

1893
server_debteliminator.md Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,10 @@
# Fund Tracker — Multi-Profile Mutual Fund & Stock Tracking Service
Device Type: **Docker Container (hosted on NAS16)**
Containers: **fundtracker_api**, **fundtracker_db**
Containers: **fundtracker_api**, **fundtracker_db** (production) / **fundtracker_qa_api**, **fundtracker_qa_db** (QA)
IP Address: **192.168.150.40** (shares NAS16's host IP)
VLAN: **50 — Lab / Servers**
Last Updated: 2026-08-19
Last Updated: 2026-10-11
---
@ -16,214 +16,485 @@ It is **not** a data source or execution platform — it pulls public price hist
---
## 🌐 Public Access
### Production
- **Domain:** `https://funds.kingdezigns.com/`
- **Proxy:** NPM on HAS (192.168.150.30) → `192.168.150.40:8000`
- **SSL:** Force SSL enabled, Let's Encrypt via NPM — same pattern as every other public KingDezigns service
- **Internal LAN access:** `http://192.168.150.40:8000/dashboard/` (unchanged, still works from VLAN 20)
- No CrowdSec/Fail2Ban changes were required — traffic proxied through NPM inherits the same protection (CrowdSec reads NPM's logs regardless of backend) as every other service behind it.
- **SSL:** Force SSL enabled, Let's Encrypt via NPM
- **Internal LAN access:** `http://192.168.150.40:8000/dashboard/`
### QA
- **Domain:** `https://funds.qa.kingdezigns.com/`
- **Proxy:** NPM on HAS (192.168.150.30) → `192.168.150.40:8001`
- **SSL:** Force SSL enabled, Let's Encrypt via NPM
- **Internal LAN access:** `http://192.168.150.40:8001/dashboard/`
No CrowdSec/Fail2Ban changes were required — traffic proxied through NPM inherits the same protection as every other service behind it.
---
## 🔀 QA → Production Deployment Workflow (v1.8.0+)
All changes follow a structured deployment path. **No changes are ever made directly to production as a development workflow.**
```
DEVELOPMENT
↓
QA (funds.qa.kingdezigns.com)
↓
Test / Verify in QA
↓
1. cp files to Production + docker restart fundtracker_api
2. Verify the site works
3. Click "Deploy to Prod" in the Dev Log on the QA site
→ auto-syncs DevLog records to prod DB
→ nav version updates for all users
```
**Critical order:** always copy files and restart FIRST, then click Deploy to Prod. If you click Deploy to Prod before copying files, the nav will show the new version number while the old code is still running.
### Promoting a tested QA version to Production
```bash
# Copy changed files (adjust list to what actually changed)
sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/config.py /Kingdezignsnas16/fundtracker/api/app/config.py
sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/main.py /Kingdezignsnas16/fundtracker/api/app/main.py
sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/routers/devlog.py /Kingdezignsnas16/fundtracker/api/app/routers/devlog.py
sudo cp /Kingdezignsnas16/fundtracker-qa/api/app/static/admin/devlog.html /Kingdezignsnas16/fundtracker/api/app/static/admin/devlog.html
sudo docker restart fundtracker_api
```
Then verify:
```bash
curl https://funds.kingdezigns.com/health
# → {"status":"ok","app_env":"production"}
sudo docker logs fundtracker_api --tail 15
```
Then click **Deploy to Prod** in the Dev Log on the QA site — this simultaneously marks the project as prod-deployed in the QA database and syncs the DevLog records to the production database.
### Post-promotion verification checklist
- `app_env: production` in `/health` response
- Scheduler registered in logs: `Added job "sync_and_report"` and `Scheduler started (APP_ENV=production)`
- No QA banner visible on the production site
- Production site loads and functions normally
- Nav footer shows the new version number
---
## 🖥️ Architecture
### Stack
- **API:** FastAPI (Python 3.12), Docker container `fundtracker_api`
- **Database:** PostgreSQL 16 (Alpine), Docker container `fundtracker_db`, bind-mounted at `/opt/fundtracker/pgdata`
- **API:** FastAPI (Python 3.12), Docker container `fundtracker_api` (prod) / `fundtracker_qa_api` (QA)
- **Database:** PostgreSQL 16 (Alpine), separate containers and storage per environment
- **Frontend:** Vanilla HTML/JS/CSS (no build step), served directly by FastAPI's `StaticFiles` mount at `/dashboard/`
- **Scheduler:** APScheduler, in-process (not an OMV Scheduled Job) — runs the daily sync + report job inside the `fundtracker_api` container itself
- **Market data:** Yahoo Finance via the `yfinance` library, using a `curl_cffi` session with Chrome browser impersonation (see Known Issues below — this is required, not optional)
- **Scheduler:** APScheduler, in-process — runs the daily sync + report job inside the API container (production only; disabled in QA)
- **Market data:** Yahoo Finance via the `yfinance` library, using a `curl_cffi` session with Chrome browser impersonation (required — Yahoo's bot detection blocks the default HTTP client)
### Environment Configuration (v1.7.0+)
A single authoritative environment flag controls all environment-specific behaviour:
| Setting | Production | QA |
|---|---|---|
| `APP_ENV` | `production` | `qa` |
| Automatic stock sync | ✅ Enabled | ❌ Disabled |
| Scheduled emails | ✅ Enabled | ❌ Suppressed |
| Manual stock sync endpoint | Available | Available |
| QA banner in UI | Absent | ✅ Amber banner |
| `/api/env-info` endpoint | `is_qa: false` | `is_qa: true` |
| DevLog sync to prod DB | ❌ Not available | ✅ Available (via `PROD_DATABASE_URL`) |
**`APP_ENV` is the only flag.** There are no `IS_DEV`/`IS_PROD` split flags — any unrecognised value defaults to `production` so the live site can never be left in a broken state.
### Email behaviour in QA
- `send_email()` in `mailer.py` accepts a `force` parameter (default `False`)
- Automatic/scheduled sends return `False` silently in QA without touching SMTP
- Explicit manual actions (password reset) use `force=True` and still deliver
- Any QA email that does send has `[QA TEST]` prepended to the subject
### Data model — shared securities, private watchlists
The core design decision: **security data is shared across all profiles, personal data is private.**
| Concept | Table | Shared or private | Contains |
|---|---|---|---|
| Security | `instruments` | **Shared** — one row per ticker, regardless of how many profiles track it | ticker, name, category, group tag, price history (via `price_points`), benchmark link |
| Watchlist entry | `watchlist_entries` | **Private** per profile | is_held, held_since, cost_basis — a profile's personal relationship to a shared security |
| Metric snapshot | `metric_snapshots` | Shared (security-level) | Daily-recorded quality/opportunity/combined/rebound scores, used for trend detection |
| Settings | `settings` | Private per profile | Currently just each profile's rebalance date |
**Practical effect:** if two profiles both track GOOGL, its price history is synced exactly once and shared instantly between them — adding a ticker someone else already tracks is immediate, no re-sync wait, no duplicate Yahoo API traffic. Only `is_held`/`cost_basis`/which-tickers-you-track are private; ticker, name, group, and all performance scores are identical for every profile tracking that security.
| Security | `instruments` | **Shared** — one row per ticker | ticker, name, category, group tag, price history, benchmark link |
| Watchlist entry | `watchlist_entries` | **Private** per profile | is_held, held_since, cost_basis |
| Metric snapshot | `metric_snapshots` | Shared (security-level) | Daily-recorded quality/opportunity/combined/rebound scores |
| Settings | `settings` | Private per profile | Each profile's rebalance date |
### Multi-profile auth
- Session-cookie based (httponly, `SameSite=Strict`), **not** JWT-in-localStorage — a cookie can't be read by injected JavaScript, meaningfully reducing XSS token-theft risk for a public-facing app
- Session-cookie based (httponly, `SameSite=Strict`), **not** JWT-in-localStorage
- Passwords hashed with `bcrypt`
- 5 failed login attempts locks the account for 15 minutes
- Forced password change on any seeded or admin-created account — cannot be skipped
- Admin role can create/delete/promote accounts, force password resets, and view the anonymized cross-profile Census (see below) — but is **not** shown other profiles' actual holdings or cost basis by design
- Admin role can create/delete/promote accounts, force password resets, and view the anonymized cross-profile Census
---
## 📊 Scoring Methodology
All scores are computed from price history only (no fundamentals data). Four are per-security (shared, identical for every profile); one is per-holding (private).
All scores are computed from price history only (no fundamentals data).
### Quality score (0–100)
Long-run risk-adjusted strength, deliberately blind to short-term noise:
Long-run risk-adjusted strength:
- 35% annualized Sharpe ratio
- 20% annualized Sortino ratio (downside-only volatility)
- 20% annualized Sortino ratio
- 25% CAGR
- 20% consistency (% of historical rolling windows, of the selected length, that were positive)
- 20% consistency (% of historical rolling windows that were positive)
Requires 30+ price points to compute; below that, returns null rather than a misleading number.
Requires 30+ price points; below that returns null.
### Opportunity score (0–100)
`0.6 × quality + 0.4 × depressed-ness`. Depressed-ness requires **both** of the following to agree (via `min()`, not an average) — this was a deliberate fix after an early version let a low-volatility fund sitting exactly at its 52-week high still score as a strong "opportunity" purely on quality alone:
1. `current_return_zscore` — is the current rolling-window return unusual *for this specific security's own history*
2. `drawdown_from_52wk_high_pct` — is it actually below its recent peak, not just statistically unusual
`0.6 × quality + 0.4 × depressed-ness`. Depressed-ness uses `min()` of:
1. `current_return_zscore` — is the current rolling return unusual for this security's own history
2. `drawdown_from_52wk_high_pct` — is it actually below its recent peak
### Combined score (0–100)
Harmonic mean of quality and opportunity (not a plain average) — deliberately punishes imbalance, so a security only scores high here if it's strong on **both** axes, not exceptional on one while mediocre on the other.
Harmonic mean of quality and opportunity — punishes imbalance.
### Rebound score (0–100) — the core "proven leader, currently crashed" signal
Answers a different question than opportunity score: *does this security normally rank near the top of its peer group by raw return, and has it recently fallen hard in that ranking?* Reconstructed retroactively from price history already on file (no waiting for new data to accumulate) by:
1. Computing every security's rolling-window return, for every date, within its shared group tag (e.g. all `STOCK`-tagged securities)
2. Ranking them against each other on every date → a full history of peer-relative percentile rank per security
3. Comparing today's percentile to the security's own historical average percentile
4. Combining "how strong is it historically" and "how far has it fallen right now" via harmonic mean, same imbalance-punishing logic as combined score
Requires a peer group of 5+ securities sharing the same group tag to compute at all.
### Rebound score (0–100)
Does this security normally rank near the top of its peer group by raw return, and has it recently fallen hard in that ranking? Requires a peer group of 5+ securities sharing the same group tag.
### Buy / Sell / Hold signal (held positions only)
A simple, explainable, threshold-based heuristic — not a black box, and explicitly documented as a screening aid rather than a trade instruction:
- **SELL** if quality has fallen below 40, or dropped 15+ points in the trailing 7 days, or the position is deeply below its own normal range with no rebound signal backing it up
- **BUY** (add to position) if opportunity ≥ 65 with quality ≥ 60, or rebound score ≥ 65
- **HOLD** otherwise
Trend-based triggers (the 7-day quality delta) only become meaningful once daily snapshots have accumulated for about a week post-deployment — this is a genuine cold-start limitation, not a bug.
Simple threshold-based heuristic — screening aid, not a trade instruction.
### Quality lookback (adjustable, default 3 years)
All of the above can be restricted to a trailing window (6mo/1yr/2yr/3yr/5yr/all) rather than always using full history. This matters: a fund that compounded fast for several early years and has since flattened out will look artificially strong if scored on all-time history — the early years hide what it's actually doing now. Verified with a synthetic test: a fund with 4 strong years then 1 flat year scored 84.6 quality on all-history, 25.9 restricted to the trailing year.
All scores can be restricted to a trailing window (6mo/1yr/2yr/3yr/5yr/all).
---
## 📋 Dev Log — Auto-Versioning System (v1.8.0)
### Overview
The Dev Log tracks all projects through a QA → Production pipeline with automatic version assignment. Versions are never manually entered — they are calculated and assigned at deployment time.
### Update Types
| Type | Version Bump | Use For |
|---|---|---|
| Minor | +0.0.1 | Normal incremental changes |
| Major | +0.1.0 | Larger feature / functionality changes |
| Platform | +1.0.0 | Significant platform-level changes |
| No Version | no bump | Changes that should not count as a version (hotfixes, config tweaks) |
### Lifecycle
```
Create Project (select update type)
↓
Queue (no version assigned yet)
↓
Deploy to QA → version auto-assigned based on update type + current highest version
↓
QA column (grouped by version, collapsible cards)
↓
Deploy to Prod → same version used, DevLog records auto-synced to prod DB
↓
Production column
```
### Nav version behaviour
- The nav footer version updates **only when a project is deployed to Production** — not on QA deploy
- This is intentional: the nav reflects what is actually live in production, not what's in QA
- The Dev Log page shows both the current QA version and Production version in the env info bar at the top
### DevLog DB sync (QA → Production)
- **Automatic per-project sync:** clicking "Deploy to Prod" in the Dev Log auto-syncs that project's version row and task row to the production database — no manual SQL needed
- **One-time bulk sync:** `POST /admin/devlog/sync-to-prod` — available via the "↑ Sync DevLog to Prod DB" button visible on the Dev Log page in QA only. Safe to run multiple times (upserts by version_number and title+created_at)
- Sync is **non-fatal** — if the prod DB connection fails, the QA-side deploy still succeeds and an error is logged
### Docker network configuration (required for sync)
The QA API container must be on the same Docker network as the production DB container. Configured in the QA compose file:
```yaml
# In qa_api service:
networks:
- default
- fundtracker_prod
# At bottom of compose file:
networks:
fundtracker_prod:
external: true
name: fundtracker_default
```
`PROD_DATABASE_URL` in the QA compose environment points at the production DB by container name:
```
PROD_DATABASE_URL=postgresql+psycopg2://fundtracker:Valerie8545@fundtracker_db:5432/fundtracker
```
Production compose does **not** have `PROD_DATABASE_URL` — sync endpoints return 503 in production by design.
### Dev Log API endpoints
| Endpoint | Purpose |
|---|---|
| `GET /admin/devlog/projects` | List all projects |
| `POST /admin/devlog/projects` | Create project (queue entry) |
| `PATCH /admin/devlog/projects/{id}` | Edit title, category, update_type, notes, status |
| `DELETE /admin/devlog/projects/{id}` | Delete (queue only — cannot delete deployed projects) |
| `POST /admin/devlog/projects/{id}/deploy-qa` | Assign next version + deploy to QA |
| `POST /admin/devlog/projects/{id}/deploy-prod` | Promote to Production + auto-sync to prod DB |
| `POST /admin/devlog/projects/{id}/undeploy-qa` | Roll back QA deployment |
| `POST /admin/devlog/projects/{id}/undeploy-prod` | Roll back Production deployment |
| `POST /admin/devlog/sync-to-prod` | Bulk sync all DevLog data to prod DB (QA only) |
| `GET /admin/devlog/versions` | List all versions |
| `PATCH /admin/devlog/versions/{id}` | Edit version label/notes |
| `GET /admin/devlog/deployed` | Current production version (used by nav footer) |
| `GET /admin/devlog/qa-version` | Current QA version |
---
## 🔐 Admin Features
### Census (anonymized cross-profile leaderboard)
`Admin → Census` page. Aggregates every tracked security across **all** profiles, showing how many profiles track it and its shared performance scores — deliberately does **not** reveal which specific profile tracks what, consistent with the private-watchlist design above.
`Admin → Census` page. Aggregates every tracked security across all profiles — does not reveal which specific profile tracks what.
### Legal document versioning
Two independently-versioned, admin-editable documents, stored in the database:
- **Terms of Use** — gated immediately after login, blocks all dashboard access until accepted
- **Investment Disclaimer** — gated specifically before adding any ticker to a watchlist (not a one-time login gate)
Two independently-versioned, admin-editable documents:
- **Terms of Use** — gated immediately after login
- **Investment Disclaimer** — gated specifically before adding any ticker
Publishing a new version (`Admin → Accounts → Legal documents`) **immediately** requires every profile to re-accept before continuing — acceptance is tracked per specific version number, so a version bump is itself the "flag everyone to re-agree" mechanism, no separate manual flag needed. An admin can also force one specific account to re-accept without republishing for everyone.
> **Not a substitute for actual legal review.** The shipped default text is comprehensive boilerplate covering no-liability-for-losses, educational-use-only, no-fiduciary-relationship, and indemnification — drafted carefully, but worth having an attorney glance at given this is a public-facing tool touching real investment decisions.
Publishing a new version immediately requires every profile to re-accept.
---
## 💼 Portfolio / Transaction Tracking (added, undated prior session — first documented here 2026-08-19)
## 💼 Portfolio / Transaction Tracking
In addition to the shared-security screening/scoring system described above, Fund Tracker also includes a full **buy-lot/sale/split transaction register** per profile — this had been built in an earlier session but was never previously written up in this file. It lives alongside (not instead of) the scheduler, pricing/NAV sync, auth, admin functionality, settings, and watchlist behavior documented elsewhere in this file.
Full buy-lot/sale/split transaction register per profile.
### Data model
- **Buy lots** — each purchase is its own row: original quantity, remaining quantity, buy price, buy fees, notes/source. Selling from a lot reduces its remaining quantity but the lot itself is never deleted.
- **Sales** — recorded as their own rows, linked to the buy lot(s) they draw down via **sale allocations**, so the relationship between a sale and the lot(s) it consumed is preserved.
- **Matching methods** — FIFO, LIFO, and Specific Lot Identification (user picks exact per-lot quantities, validated to sum to the total sold) are all supported at time of sale.
- **Lot status** — `ACTIVE` (untouched), `PARTIAL` (some shares sold, some remain), `CLOSED` (fully sold) — a closed lot stays visible in the register rather than disappearing, preserving full history.
- **Stock splits / reverse splits** — a recorded split only adjusts share count and per-share cost basis on lots that were **active and purchased before** the split date. Lots purchased on/after the split date, and lots already fully sold before the split date, are left untouched.
- **Buy lots** — each purchase is its own row: original quantity, remaining quantity, buy price, buy fees, notes/source
- **Sales** — linked to buy lot(s) via sale allocations; FIFO, LIFO, and Specific Lot Identification supported
- **Lot status** — `ACTIVE`, `PARTIAL`, `CLOSED`
- **Stock splits** — only adjusts lots active and purchased before the split date
### Key endpoints
| Endpoint | Purpose |
|---|---|
| `GET /portfolio/holdings` | Active holdings dashboard view |
| `GET/POST /portfolio/lots/{ticker}` | List / create buy lots for a ticker |
| `PATCH /portfolio/lots/{lot_id}` | Edit a buy lot — only allowed while it has zero sale allocations (see locking, below) |
| `DELETE /portfolio/lots/{lot_id}` | Delete a buy lot (same zero-allocation restriction) |
| `GET/POST /portfolio/sales` | List / record sales (FIFO/LIFO/Specific ID) |
| `DELETE /portfolio/sales/{sale_id}` | Delete a sale — **restores** the allocated quantity back to the affected buy lot(s), which also unlocks them for editing |
| `GET/POST /portfolio/lots/{ticker}` | List / create buy lots |
| `PATCH /portfolio/lots/{lot_id}` | Edit a buy lot (zero-allocation only) |
| `DELETE /portfolio/lots/{lot_id}` | Delete a buy lot (zero-allocation only) |
| `GET/POST /portfolio/sales` | List / record sales |
| `DELETE /portfolio/sales/{sale_id}` | Delete a sale — restores allocated quantity to lot(s) |
| `GET/POST /portfolio/splits` | List / apply stock splits |
| `GET /portfolio/register` | The full buy-lot register: each lot with its associated sale allocations, current price, unrealized G/L, realized G/L, and status — this is what the Portfolio page renders |
| `POST /portfolio/import/csv` | Bulk import buys/sells from pasted CSV text |
| `GET /portfolio/register` | Full lot+sale register view |
| `POST /portfolio/import/csv` | Bulk import from CSV |
### Editing & locking
A buy lot can be edited or deleted only while it has **no** sale allocations against it — once a sale references a lot, that lot locks (shown as 🔒 in the UI) to protect the historical/tax record. The recovery path is to delete the associated sale first (which restores the shares to the lot), then edit/delete the now-unlocked lot.
### Portfolio UI — three-level collapsible hierarchy (updated 2026-08-19)
The Portfolio page (`/dashboard/portfolio.html`) renders the register as **Ticker → Buy Lot → Sale(s)**, both levels collapsible:
- **Ticker rows** — one row per ticker held, **collapsed by default** on page load. Clicking the row's twistie (▶/▼) expands it to reveal that ticker's individual buy lots. This was the 2026-08-19 change — previously every buy lot for every ticker rendered at once, making the register long and hard to scan.
- **Buy lot rows** — nested under their ticker once expanded. Each lot that has associated sales shows its own twistie (e.g. `▶ 2`) which expands to reveal the sale row(s) consumed from that specific lot. This twistie already existed prior to 2026-08-19 and was left unchanged.
- Expanding a ticker does not auto-expand its lots' sale twisties, and collapsing a ticker hides its lots' sale rows regardless of their own expand/collapse state — the two levels are independent, but a lot's sales can only ever be visible while its parent ticker is also expanded.
- Implementation notes: both expand states are tracked client-side only (`_expandedTickers` and `_expanded` JS `Set`s in `portfolio.html`), not persisted to the backend or across page reloads. Toggling is done via direct DOM show/hide rather than a full table re-render, so toggling one ticker/lot does not disturb the expand state of others.
- **Deployment note:** this was a frontend-only change to `api/app/static/portfolio.html` — no router, schema, or model changes. Deployed via the standard code-only pattern: file copied to a `/tmp` scratch path via `scp`, moved into `/Kingdezignsnas16/fundtracker/api/app/static/` with `sudo cp` (the project directory is root-owned), then `sudo docker restart fundtracker_api` (plain restart is sufficient since `app/` is bind-mounted — no rebuild needed for a static-file-only change).
### Known deployment gotchas (from earlier portfolio build work — kept here to avoid repeating)
- `models.py` has previously broken from using `Decimal` or `CheckConstraint` without importing them — always verify imports after any model change before restarting the container.
- Files transferred from a stale `/tmp` copy have previously overwritten newer code (e.g. an old portfolio router missing the `register` endpoint) — always confirm the source file being copied is the actual latest version, not a leftover scratch copy.
- `BuyLotEdit` (in `schemas.py`) has previously been referenced by `portfolio.py` before being defined — a reminder that schema and router changes need to land together, not the router first.
- General rule reaffirmed: after any deploy, check container startup logs, hit `/health`, then explicitly test the specific endpoint/UI behavior that changed — don't assume a clean restart means the change is live and correct.
### Admin — user account email management
Two admin endpoints exist for managing account emails, separate from the Census/legal-document admin features described above:
```
PATCH /admin/users/{id}/email
GET /admin/users/{id}/email-changes
```
Email changes are logged in an audit trail that requires a reason at time of change.
### Portfolio UI — three-level collapsible hierarchy
**Ticker (collapsed by default) → Buy Lot → Sale(s)**
---
## 🐳 Docker Configuration
### Production
Managed via OMV → Services → Compose, project `fundtracker`, at `/Kingdezignsnas16/fundtracker/`.
### Key environment variables
| Variable | Purpose |
|---|---|
| `DATABASE_URL` | Postgres connection string |
| `SYNC_HOUR_UTC` / `SYNC_MINUTE_UTC` | Daily sync+report time (default 06:00 UTC) |
| `SMTP_HOST/PORT/USER/PASSWORD/FROM` | Same Zoho account used by every other KingDezigns notification |
| `ADMIN_SEED_USERNAME/PASSWORD/EMAIL` | Bootstrap admin, only used if the `users` table is completely empty |
| `SESSION_TTL_DAYS` | Login session length (default 14) |
| `COOKIE_SECURE` | **Must be `true`** now that this is exposed externally over HTTPS — `false` is LAN-testing-only and sends credentials in cleartext if left on over plain HTTP |
| `PUBLIC_BASE_URL` | Should be `https://funds.kingdezigns.com` — used to build password-reset email links |
| `REPORT_WINDOW_DAYS/LOOKBACK_YEARS/TOP_N` | Daily email report defaults |
| Container | Name | Port |
|---|---|---|
| API | `fundtracker_api` | `8000:8000` |
| Database | `fundtracker_db` | (internal only) |
### Deployment pattern (established across multiple rounds of iteration)
- **Code-only changes** (edits inside `api/app/`): copy the updated `app/` folder into the OMV project directory, then `sudo docker restart fundtracker_api`. A plain restart is sufficient since `app/` is bind-mounted.
- **New Python dependencies** (`requirements.txt` changes): a restart is **not** enough — requires `docker compose build --no-cache api` followed by `up -d`, since dependencies are baked into the image at build time.
- **Compose YAML / environment variable changes**: requires `up -d` (recreate), not `restart` — a plain restart reuses the old in-memory environment. This distinction caused real deploy failures twice during development (once for the `curl_cffi` fix, once for the `bcrypt` addition) before being nailed down.
- Because `/Kingdezignsnas16/fundtracker/` is root-owned (`drwx------`, contains DB credentials), file transfers land in a `rufusking`-writable scratch path first (e.g. `/tmp/ft_upload/`), then get moved into place with `sudo cp -r`.
- **Compose file:** `/Kingdezignsnas16/fundtracker/fundtracker.yml` (OMV-managed, do not hand-edit)
- **pgdata:** `/opt/fundtracker/pgdata`
- **DB credentials:** user `fundtracker`, db `fundtracker`, password `Valerie8545`
- **Network:** `fundtracker_default` — production DB is reachable by container name `fundtracker_db` from any container on this network
### QA
Managed via OMV → Services → Compose, project `fundtracker-qa`, at `/Kingdezignsnas16/fundtracker-qa/`.
| Container | Name | Port |
|---|---|---|
| API | `fundtracker_qa_api` | `8001:8000` |
| Database | `fundtracker_qa_db` | (internal only) |
- **Compose file:** `/Kingdezignsnas16/fundtracker-qa/fundtracker-qa.yml` (OMV-managed, do not hand-edit)
- **pgdata:** `/opt/fundtracker_qa/pgdata` (owned by UID/GID 70:70 — the postgres user on this host)
- **DB credentials:** user `fundtracker_qa`, db `fundtracker_qa`, password `Valerie8545_qa`
- **Service names in compose:** `qa_db` and `qa_api` (not `db`/`api` — OMV named them differently)
- **Networks:** QA API is on both `default` (its own network) and `fundtracker_prod` (external, mapped to `fundtracker_default`) — required for DevLog DB sync to reach the prod DB container
### Key environment variables (both environments)
| Variable | Production | QA | Purpose |
|---|---|---|---|
| `APP_ENV` | `production` | `qa` | Single environment flag |
| `DATABASE_URL` | prod connection string | QA connection string | Primary DB |
| `PROD_DATABASE_URL` | *(not set)* | prod connection string | DevLog sync target |
| `SYNC_HOUR_UTC` / `SYNC_MINUTE_UTC` | `6` / `0` | (ignored in QA) | Daily sync+report time |
| `SMTP_*` | Zoho creds | Zoho creds (suppressed in QA) | Email |
| `ADMIN_SEED_USERNAME/PASSWORD/EMAIL` | Bootstrap admin | Bootstrap admin | Only used if `users` table empty |
| `SESSION_TTL_DAYS` | `14` | `14` | Login session length |
| `COOKIE_SECURE` | `true` | `true` | Required for HTTPS |
| `PUBLIC_BASE_URL` | `https://funds.kingdezigns.com` | `https://funds.qa.kingdezigns.com` | Password reset links |
| `PRIMARY_ADMIN_USERNAME` | `rufusking` | `rufusking` | Cannot be deleted or demoted |
| `TRUSTED_PROXY_IP` | `192.168.150.30` | `192.168.150.30` | Real IP forwarding from NPM |
### Deployment patterns
- **Code-only changes** (edits inside `api/app/`): copy updated files into the project directory, then `sudo docker restart fundtracker_api`. Plain restart is sufficient since `app/` is bind-mounted.
- **New Python dependencies** (`requirements.txt` changes): requires `docker compose build --no-cache api` followed by `up -d`.
- **Compose YAML / environment variable changes**: requires `up -d --force-recreate` — a plain restart reuses the old in-memory environment.
- **Structural DB migrations**: take a `pg_dump` backup first.
### QA-specific compose commands
```bash
# Start QA
sudo docker compose -f /Kingdezignsnas16/fundtracker-qa/fundtracker-qa.yml up -d
# Restart QA API only (code change)
sudo docker restart fundtracker_qa_api
# Force-recreate QA API (compose/env change)
sudo docker compose -f /Kingdezignsnas16/fundtracker-qa/fundtracker-qa.yml up -d --force-recreate qa_api
# View QA logs
sudo docker logs fundtracker_qa_api --tail 30
# View QA DB logs
sudo docker logs fundtracker_qa_db --tail 20
```
### Database migrations
Two tiers, by risk:
- **Additive** (`ADD COLUMN IF NOT EXISTS`) — safe, runs on every startup, no backup needed.
- **Structural** (e.g. the shared-security/private-watchlist split, the per-profile settings conversion) — genuinely restructures data, including column drops. These are idempotent (safe to run repeatedly) but a `pg_dump` backup is taken before deploying any update in this category, restorable via `psql` into a fresh container.
- **Structural** — requires a `pg_dump` backup before deploying.
```bash
# Production backup
sudo docker exec fundtracker_db pg_dump -U fundtracker fundtracker | gzip > /tmp/fundtracker-prod-$(date +%Y%m%d).sql.gz
# QA backup
sudo docker exec fundtracker_qa_db pg_dump -U fundtracker_qa fundtracker_qa | gzip > /tmp/fundtracker-qa-$(date +%Y%m%d).sql.gz
```
### Re-cloning production data into QA
When QA needs a fresh copy of production data:
```bash
sudo docker exec fundtracker_db pg_dump -U fundtracker fundtracker \
| sudo docker exec -i fundtracker_qa_db psql -U fundtracker_qa fundtracker_qa
```
The `ERROR: role "fundtracker" does not exist` messages are harmless — ownership assignment fails but all table structure and data copies correctly.
---
## 📊 Watch Alerts — Intraday BUY Signal Monitoring (v1.9.0)
Per-profile, intraday monitoring of up to 5 tickers for BUY signal transitions. Sends one email alert when a signal changes *to* BUY — not repeatedly while it stays BUY. Once the signal leaves BUY and returns, a new alert fires.
- **Module:** `watch_alerts.py` — self-contained: migration, scheduler job, API router
- **DB table:** `watch_alert_monitors` — `user_id`, `ticker`, `last_signal`, `last_checked_at`, `alert_sent_at`
- **Poll interval:** per-user setting (`watch_poll_minutes` in the `settings` table, valid: 5/10/15/30/45/60). Scheduler job fires on a 5-minute base tick; each monitor's `last_checked_at` gates whether the user's chosen interval has elapsed.
- **Market hours:** `pandas-market-calendars` (NYSE calendar) — correctly excludes weekends AND NYSE holidays. Graceful fallback to weekday-only check if library unavailable.
- **Price refresh:** `period="5d"` Yahoo pull per unique monitored ticker — lightweight, not a full 5-year re-download.
- **Live dashboard row refresh:** frontend polls `/watch-alerts/monitors` on the user's chosen interval and surgically updates only the Signal cell for monitored tickers — no full page reload.
- **New dependency:** `pandas-market-calendars>=4.3.1` added to `requirements.txt` — requires image rebuild on first deploy.
- **UI panel:** "Watch Alerts" panel on dashboard — single row layout: interval dropdown | ticker chips with signal badges | Add input | Track button. Market Open badge updates every minute client-side.
### Watch Alerts API endpoints
| Endpoint | Purpose |
|---|---|
| `GET /watch-alerts/monitors` | List user's monitors with last_signal |
| `POST /watch-alerts/monitors` | Add ticker (max 5, ticker must exist in instruments) |
| `DELETE /watch-alerts/monitors/{ticker}` | Remove monitor |
| `GET /watch-alerts/poll-interval` | Get user's poll interval (minutes) |
| `PUT /watch-alerts/poll-interval` | Set user's poll interval |
---
## 🩺 Ticker Health Panel (v1.9.0)
Admin-only self-service panel to identify and remediate broken or stale instruments without SSH or psql access.
- **Page:** `Admin → Ticker Health` (`/dashboard/admin/ticker-health.html`)
- **Backend:** `ticker_health_router` appended to `admin.py`, registered in `main.py`
- **Migration:** `migrate_sync_metadata()` in `migrations.py` — adds `last_sync_at`, `last_sync_rows`, `last_sync_error` to `instruments` table via `ADD COLUMN IF NOT EXISTS`. Safe, additive, no backup needed.
### Flags surfaced
| Flag | Condition |
|---|---|
| `no_prices` | 0 price points ever stored |
| `last_sync_empty` | Most recent sync returned 0 rows |
| `never_synced` | `last_sync_at` is NULL |
| `stale` | `last_sync_at` > 3 days ago |
| `suspicious_symbol` | Ticker contains `.` `/` `\` `,` or space |
| `sync_error` | `last_sync_error` is non-null |
### Admin actions (all inline, no DB access needed)
- **↻ Re-sync** — force immediate Yahoo sync, shows row count or error inline
- **✎ Rename** — inline ticker rename (e.g. `BRK.B` → `BRK-B`), immediately re-syncs to verify, updates `WatchAlertMonitor` rows, logs to audit log
- **✕ Delete** — dry-run first (shows price count + affected profile count), then `?confirm=true` to execute. Cascades: price points, watchlist entries, metric snapshots, watch alert monitors.
### Sync metadata stamping
`data_fetch.sync_instrument_from_yahoo()` now stamps `last_sync_at`, `last_sync_rows`, and `last_sync_error` on every call — success, empty, and exception all leave a clear trail. Covers daily job and admin force-syncs.
---
## 📈 Signal Logic Refinement — WATCH Threshold Tightening (v1.9.0)
WATCH was previously a catch-all "else" for non-held securities — anything that didn't trigger BUY/SELL/null got WATCH, which was the majority of the portfolio. Reclassified as a high-value alert requiring positive evidence.
**New WATCH criteria (non-held only, all require quality ≥ 55):**
- Opportunity ≥ 55 — a real dip is developing
- Z-score ≤ -1.2 — return running meaningfully below normal (early-warning dip)
- Rebound ≥ 50 — moderate peer-relative anomaly forming
**Securities that now get null instead of WATCH:** solid quality, normal z-score, no dip forming, no peer anomaly — "nothing to see here" is correctly represented as no signal.
**MUTF null case fully preserved:** `quality_score is None` still returns null for non-held (the "do not touch" marker). No change to that path.
**Key threshold constants** (all in `signals.py`, named for easy adjustment):
- `_WATCH_QUALITY_FLOOR = 55.0`
- `_WATCH_OPPORTUNITY = 55.0`
- `_WATCH_ZSCORE = -1.2`
- `_WATCH_REBOUND = 50.0`
---
## 🖥️ Dashboard Layout Consolidation (v1.9.0)
View Controls and Add Ticker panels merged into a single split panel (left/right) to reduce vertical space. Export/Import, Send Report, and Held Only moved from a third row under View Controls to a second row under Add Ticker (right column). "Send email report now" button renamed to "Send Report".
---
## ⚠️ Known Issues & Fixes Already Shipped
- **Yahoo Finance blocking (fixed):** `yfinance`'s default HTTP client gets silently blocked by Yahoo's bot detection with increasing frequency — the library misreports this as "no data" rather than "blocked." Fixed by routing all requests through a `curl_cffi` session impersonating a real Chrome browser's TLS fingerprint.
- **Bogus-ticker crash (fixed):** a nonexistent ticker could make `yfinance`'s internal metadata lookup throw an unhandled exception (a JSON decode error) instead of just returning empty data, crashing the add-ticker request entirely. Now caught and treated as "0 rows synced," which correctly triggers the verification-failure flow instead.
- **Ticker verification with override:** adding a brand-new ticker attempts a real sync as verification. Zero rows returned prompts a warning with an explicit "add anyway" override (rather than a hard block) — specifically to handle legitimate cases like a recent ticker rename Yahoo hasn't caught up to yet (e.g. Siemens Energy's SMNEY → SMERY change).
- **Rate-limit-driven data source risk:** noted, not yet acted on — if Yahoo's blocking becomes more aggressive over time, alternative data sources may need evaluation. Deferred as a future consideration.
- **Yahoo Finance blocking (fixed):** `yfinance`'s default HTTP client gets silently blocked by Yahoo's bot detection. Fixed by routing all requests through a `curl_cffi` session impersonating a real Chrome browser's TLS fingerprint.
- **Bogus-ticker crash (fixed):** a nonexistent ticker could make `yfinance`'s internal metadata lookup throw an unhandled exception. Now caught and treated as "0 rows synced."
- **Ticker verification with override:** adding a brand-new ticker attempts a real sync as verification. Zero rows returned prompts a warning with an explicit "add anyway" override.
---
## 💾 Backup
- `/opt/fundtracker/pgdata` (bind-mounted Postgres data) can fold into `nas16-backup.sh` the same way Forgejo's data was — not yet formally added as of this writing.
- A raw file-copy backup of a *live* Postgres directory can be inconsistent; `pg_dump` is the reliable method (see Deployment pattern above). Given nearly all price data is re-derivable by re-syncing from Yahoo, a stale/imperfect backup mainly costs a re-sync, not real data loss — the one exception is user accounts, watchlist memberships (which securities each profile tracks), cost basis, and legal-acceptance records, which are **not** re-derivable and are the actual reason to keep backups current.
- `/opt/fundtracker/pgdata` (production) and `/opt/fundtracker_qa/pgdata` (QA) can both fold into `nas16-backup.sh`.
- Use `pg_dump` rather than raw file-copy for reliable backups of live Postgres data.
- The one exception to "re-syncable from Yahoo": user accounts, watchlist memberships, cost basis, and legal-acceptance records — keep backups current for these.
---
## 🧠 Summary for AI Systems
- **MANDATORY (added 2026-10-11):** every delivery of Fund Tracker files must OPEN with the exact `scp` → `sudo cp` (QA path `/Kingdezignsnas16/fundtracker-qa/api/app/...`) → `sudo docker restart fundtracker_qa_api` command block, with real file names and restart-vs-rebuild stated, before any explanation — then, after QA passes, the production copy + `sudo docker restart fundtracker_api` + Deploy to Prod order described above. See `server_debteliminator.md` §3a-0 for the template.
- Fund Tracker = **multi-profile mutual fund/stock tracking web app**, Docker Compose on NAS16, VLAN 50.
- Public at `https://funds.kingdezigns.com/` via NPM on HAS, Force SSL. Also reachable internally at `http://192.168.150.40:8000/dashboard/`.
- Two containers: `fundtracker_api` (FastAPI) and `fundtracker_db` (Postgres 16).
- **Shared security data, private watchlists**: ticker/price history/group tag are shared across all profiles; is_held/cost_basis/which-tickers-tracked are private per profile.
- Scoring: quality (risk-adjusted, security-level) → opportunity (quality + genuine dip, requires both z-score AND drawdown to agree) → combined (harmonic mean of quality+opportunity) → rebound (peer-relative "usually top of its group, currently collapsed" detector, reconstructed retroactively from existing price history).
- Buy/Sell/Hold signals apply only to positions flagged `is_held` — simple threshold heuristic, documented as a screening aid, not a trade instruction.
- **Two environments:** production (`funds.kingdezigns.com`, port 8000, containers `fundtracker_api`/`fundtracker_db`) and QA (`funds.qa.kingdezigns.com`, port 8001, containers `fundtracker_qa_api`/`fundtracker_qa_db`). Both run on NAS16 simultaneously with completely separate databases.
- **Single environment flag:** `APP_ENV=production` or `APP_ENV=qa`. No `IS_DEV`/`IS_PROD` flags. Unrecognised values default to `production`.
- **QA behaviour:** scheduler idle, `send_email()` suppresses automatic sends, password-reset emails use `force=True` and still deliver, amber "⚠️ QA ENVIRONMENT" banner in UI, DevLog sync to prod DB available.
- **Production behaviour:** scheduler runs at 06:00 UTC, emails send normally, no QA banner, no `PROD_DATABASE_URL`.
- **Deployment workflow:** changes → QA → test → (1) cp files to prod + docker restart → (2) verify → (3) click Deploy to Prod in Dev Log on QA site. Never reverse steps 1 and 3.
- **Dev Log auto-versioning (v1.8.0):** projects created in Queue with update_type (minor/major/platform/no-version). Deploy to QA auto-assigns next version. Deploy to Prod uses same version + auto-syncs DevLog records to prod DB. Nav version only updates on Deploy to Prod. Cards collapsed by default, click to expand.
- **DevLog DB sync:** QA API is joined to `fundtracker_default` network so it can reach `fundtracker_db` by container name. `PROD_DATABASE_URL` set in QA compose. Auto-syncs on Deploy to Prod. Bulk sync via `POST /admin/devlog/sync-to-prod` (button on Dev Log page in QA only). Non-fatal if prod DB unreachable.
- **QA compose network config:** `qa_api` service has `networks: [default, fundtracker_prod]`; bottom of compose declares `networks: fundtracker_prod: external: true, name: fundtracker_default`. Required for DevLog sync. If QA API can't reach prod DB, verify this network config and run `docker compose up -d --force-recreate qa_api` (not just `docker restart`).
- **`docker restart` vs `up -d --force-recreate`:** restart reuses the existing in-memory container environment — compose file changes (env vars, networks, volumes) are NOT picked up. Always use `force-recreate` after editing the compose file.
- **Production compose project:** `fundtracker` at `/Kingdezignsnas16/fundtracker/`, compose file `fundtracker.yml`, pgdata at `/opt/fundtracker/pgdata`.
- **QA compose project:** `fundtracker-qa` at `/Kingdezignsnas16/fundtracker-qa/`, compose file `fundtracker-qa.yml`, pgdata at `/opt/fundtracker_qa/pgdata` (owned 70:70), service names `qa_api`/`qa_db` in compose.
- Scoring: quality → opportunity → combined → rebound (all from price history via `yfinance`+`curl_cffi`).
- Auth: httponly session cookies, bcrypt, 5-attempt lockout, forced password change on seeded accounts.
- Admin: account management, anonymized cross-profile Census, versioned legal document publishing (version bump = automatic re-acceptance requirement for everyone).
- Market data via `yfinance` + `curl_cffi` (Chrome impersonation) — required workaround for Yahoo's bot detection, not optional.
- Deployment: code-only changes = folder swap + `docker restart`; dependency changes = rebuild; compose/env changes = `up -d`. Structural DB migrations require a `pg_dump` backup first.
- `COOKIE_SECURE=true` and `PUBLIC_BASE_URL=https://funds.kingdezigns.com` must both be set now that this is publicly exposed — leaving `COOKIE_SECURE=false` on a public HTTPS deployment would send credentials in cleartext.
- **Portfolio / transaction tracking (documented here 2026-08-19, built in an earlier session):** a full buy-lot/sale/split register sits alongside the scoring/screening system — buy lots (with remaining-qty tracking), sales (FIFO/LIFO/Specific ID matching via `/portfolio/sales`), and splits (`/portfolio/splits`, only affects lots active and purchased before the split date). `GET /portfolio/register` returns the full lot+sale view the Portfolio page renders. Lots lock against edit/delete once a sale references them — deleting the sale restores shares and unlocks the lot. CSV bulk import via `/portfolio/import/csv`. Full endpoint list and locking rules in the dedicated section above.
- **Portfolio UI updated 2026-08-19:** the register now renders as a three-level collapsible hierarchy — **Ticker (collapsed by default) → Buy Lot → Sale(s)** — instead of showing every lot for every ticker at once. Frontend-only change to `portfolio.html`, deployed via the standard code-only pattern (scp to `/tmp` → `sudo cp` into the root-owned project dir → `sudo docker restart fundtracker_api`, no rebuild required).
- **Known portfolio deployment gotchas** (missing `Decimal`/`CheckConstraint` imports in `models.py`, stale `/tmp` copies overwriting newer router code, schema/router ordering) are logged in the Portfolio section above — check there before re-diagnosing the same class of failure.
- Admin: account management, anonymized cross-profile Census, versioned legal document publishing.
- **Portfolio / transaction tracking:** buy-lot/sale/split register, FIFO/LIFO/Specific ID matching, `GET /portfolio/register`, lot locking on sale allocation.
- **Portfolio UI:** three-level collapsible hierarchy — Ticker (collapsed by default) → Buy Lot → Sale(s).
- `COOKIE_SECURE=true` and correct `PUBLIC_BASE_URL` must both be set in both environments.
- **Watch Alerts (v1.9.0):** Per-profile intraday BUY-transition monitoring. Up to 5 tickers per profile. Email fires once on BUY transition, resets when signal leaves BUY. Poll interval is per-user (5/10/15/30/45/60 min), stored in `settings` table as `watch_poll_minutes`. Scheduler base tick is 5 min; `last_checked_at` on each monitor gates the user's chosen interval. Market hours via `pandas-market-calendars` (NYSE, excludes holidays). Live dashboard row refresh on user's chosen interval — only Signal cell updated, no page reload. New dependency: `pandas-market-calendars>=4.3.1` (requires image rebuild on first deploy). Module: `watch_alerts.py`. Table: `watch_alert_monitors`.
- **Ticker Health panel (v1.9.0):** Admin-only page at `Admin → Ticker Health`. Surfaces instruments with `no_prices`, `last_sync_empty`, `never_synced`, `stale` (>3d), `suspicious_symbol`, or `sync_error` flags. Inline Re-sync, Rename (with immediate re-sync verification + audit log), and Delete (dry-run then confirm). `data_fetch.sync_instrument_from_yahoo()` now stamps `last_sync_at`/`last_sync_rows`/`last_sync_error` on every call. Migration: `migrate_sync_metadata()` adds three columns to `instruments` via `ADD COLUMN IF NOT EXISTS`. Router: `ticker_health_router` in `admin.py`.
- **WATCH signal tightened (v1.9.0):** WATCH was previously a catch-all else for non-held securities. Now requires quality ≥ 55 AND one of: opportunity ≥ 55, z-score ≤ -1.2, or rebound ≥ 50. Securities that are "fine but unexciting" now correctly return null. MUTF null (insufficient history) preserved unchanged. Thresholds are named constants at the top of `signals.py`.
- **Dashboard layout (v1.9.0):** View Controls and Add Ticker merged into one split panel. Export/Import + Send Report + Held Only moved to second row of right column. "Send email report now" → "Send Report".
---

View file

@ -4,7 +4,7 @@ Hostname: **homeassistant**
IP Address: **192.168.150.30**
VLAN: **50 — Lab / Servers**
Last Updated: 2026-08-17
Last Updated: 2026-10-02
---
@ -68,6 +68,9 @@ This placement ensures:
| 192.168.150.40:3670 | NAS16 service |
| 192.168.150.40:3000 | Forgejo — self-hosted Git server (`forgejo.kingdezigns.com`, Force SSL, see `server_forgejo.md`) |
| 192.168.150.40:8000 | Fund Tracker — multi-profile mutual fund/stock tracking web app (`funds.kingdezigns.com`, Force SSL, see `server_fundtracker.md` and `server_nas16.md`) |
| 192.168.150.40:8002 | Debt Eliminator (production) — personal debt tracking web app (`cutthecard.net` / `www.cutthecard.net`, Force SSL, see `server_debteliminator.md`) |
| 192.168.150.40:8003 | Debt Eliminator (QA) — `debt.qa.cutthecard.net`, Force SSL, see `server_debteliminator.md` |
| 192.168.150.40:3001 | Umami analytics — `stats.cutthecard.net`, Force SSL + HTTP/2, websockets off, see `server_umami.md` |
| 192.168.150.35:8080 | NAS08 service |
| 192.168.150.35:8081 | NAS08 service |
| 192.168.150.35:8082 | NAS08 service |
@ -110,7 +113,7 @@ Internet → UCG Max → NPM (192.168.150.30:80/443)
- Banned IPs are blocked before traffic ever reaches NPM or backend services
- **Email notifications are handled externally by NAS16** — not by CrowdSec's native notification system
- Native CrowdSec email notifications are **disabled** in profiles.yaml
- **Applies uniformly to every service proxied through NPM**, including Fund Tracker and Forgejo — no per-service CrowdSec configuration is required; anything routed through NPM inherits this protection automatically.
- **Applies uniformly to every service proxied through NPM**, including Fund Tracker, Forgejo, and Debt Eliminator — no per-service CrowdSec configuration is required; anything routed through NPM inherits this protection automatically.
#### Active Collections
| Collection | Protects Against |
@ -288,7 +291,7 @@ These are essential for:
## 🧠 Summary for AI Systems
- HAS = **automation hub + network reverse proxy + intrusion prevention** located in VLAN 50.
- Runs Home Assistant core, Nginx Proxy Manager (port 81), CrowdSec Agent + LAPI (port 8080), and CrowdSec Firewall Bouncer.
- NPM is the single external ingress point for all internal web services, including Forgejo and Fund Tracker.
- NPM is the single external ingress point for all internal web services, including Forgejo, Fund Tracker, and Debt Eliminator.
- CrowdSec is the single intrusion prevention layer — blocks at nftables before NPM, applies uniformly to every NPM-proxied service.
- NPM logs are read via journald using SYSLOG_IDENTIFIER `addon_a0d7b954_nginxproxymanager`.
- 60 active detection scenarios covering HTTP attacks, CVEs, brute force, and SSH.
@ -304,6 +307,8 @@ These are essential for:
- Uses Pi‑hole in VLAN 50 for DNS.
- All proxied traffic to backends appears to originate from 192.168.150.30.
- **Fund Tracker added 2026-08-17** — `funds.kingdezigns.com` → 192.168.150.40:8000, Force SSL. Full detail in `server_fundtracker.md`.
- **Debt Eliminator added 2026-08-24, rebranded 2026-09** — both domains changed: production moved from `debt.kingdezigns.com` to `cutthecard.net` / `www.cutthecard.net` → 192.168.150.40:8002, and QA moved from `debt.qa.kingdezigns.com` to `debt.qa.cutthecard.net` → 192.168.150.40:8003 (both NPM proxy hosts updated, confirmed 2026-09-15). `cutthecard.org` redirects to `cutthecard.net` at Dreamhost DNS only, not configured in NPM. Both Force SSL. Full detail in `server_debteliminator.md`.
- **Umami analytics added 2026-10-01** — `stats.cutthecard.net` → 192.168.150.40:3001, Force SSL + HTTP/2, websockets off. Public DNS via the Dreamhost A record + NAS16 DDNS script; Pi-hole local override `stats.cutthecard.net` → 192.168.150.30 (avoids NAT hairpin). No CrowdSec/firewall changes needed. Full detail in `server_umami.md`.
---

View file

@ -4,7 +4,7 @@ Hostname: **NAS08**
IP Address: **192.168.150.35**
VLAN: **50 — Lab / Servers**
Last Updated: 2026-07-25
Last Updated: 2026-10-20
---
@ -31,6 +31,7 @@ This device is a **critical infrastructure component**, supporting both internal
| /dev/sdc | Crucial BX500 (CT1000BX500SSD1) | 1TB | Data |
| /dev/sdd | Crucial BX500 (CT1000BX500SSD1) | 1TB | Data |
| /dev/sde | Crucial BX500 (CT1000BX500SSD1) | 1TB | Data |
| /dev/sdf | Crucial MX500 (CT1000MX500SSD1) | 1TB | Data — added 2026-10-19, being added to `kingdezignsnas` via RAIDZ expansion (see ZFS Pool section) |
---
@ -651,6 +652,60 @@ This setting should remain enabled if/when the Synaplan backend is deployed loca
---
## 🧱 ZFS Pool — kingdezignsnas (RAIDZ2 expansion, 2026-10-19)
### **Layout**
- Pool: `kingdezignsnas`, OpenZFS **2.4.4** (Debian backports `zfs-2.4.4-1~bpo13+1`)
- Single vdev `raidz2-0` (RAIDZ2 = two-disk parity)
- Before: 4 x Crucial BX500 1TB (raw 3.62T, ~91% full, ~297G free)
- After expansion: 4 x BX500 + 1 x Crucial MX500 1TB (`ata-CT1000MX500SSD1_2415E8A6E7AC`, `/dev/sdf`) = 5 disks
- Last clean scrub before the expansion: 2026-10-18, 0 errors (1h16m)
- Only `feature@raidz_expansion` was enabled; no full `zpool upgrade` was run, so other feature flags are still pending (the "Some supported and requested features are not enabled" notice is expected)
### **New-drive qualification (before attaching)**
The MX500 arrived with an NTFS partition (empty apart from `System Volume Information`), 963 power-on hours and ~3.2 TB written. Tests run on 2026-10-19:
1. `smartctl -a`: PASSED; 0 reallocated, 0 pending, 0 uncorrectable; lifetime remaining 100%; `UDMA_CRC_Error_Count` = 1 (watch item, did not increase)
2. SMART short + extended self-tests: completed without error
3. `badblocks -b 4096 -c 16384 -wsv -t 0x55`: one full write/read-verify pass, 0 bad blocks, empty log
4. SMART re-check after the write test: all counters unchanged
Harmless smartctl output on this model: attribute 180 (`Unused_Reserve_NAND_Blk`) normalized value 000, and "ATA error count 0 inconsistent with error log pointer".
### **Expansion procedure used**
```bash
# NAS16 sync run first so the backup copy was current (NAS16: /usr/scripts/nas/nas08_to_nas16_sync.sh)
sudo umount /dev/sdf1 2>/dev/null
sudo wipefs -a /dev/sdf
sudo partprobe /dev/sdf
sudo zpool set feature@raidz_expansion=enabled kingdezignsnas
sudo zpool attach kingdezignsnas raidz2-0 /dev/disk/by-id/ata-CT1000MX500SSD1_2415E8A6E7AC
```
Always address disks by `/dev/disk/by-id/...`, not `/dev/sdX`.
### **Status**
- Started **2026-10-19 19:59:42 EDT**. Initial estimate was ~5 hours at ~198 MB/s.
- Progress check on 2026-10-20: **36.44% (1.22T of 3.33T) at 22.8 MB/s, estimate 1 day 3 hours remaining.** Far slower than the first estimate; cause not yet diagnosed (see below). Pool stayed `ONLINE` with 0 errors.
- The expansion must not be interrupted: no reboot or power-off until `zpool status` shows it complete.
- **Extra capacity only appears when the expansion completes** (`zpool list`, `zfs list`, and therefore OMV).
### **Why it is slow / what to check**
- Expansion rewrites all existing data (~3.33T), about 4x the data of a single-disk resilver.
- Likely contributors: DRAM-less BX500 drives falling out of their SLC cache on sustained writes, the Pi's CPU doing parity work, and normal NAS08 load (Nextcloud, DNS, sync jobs) competing for the pool.
- Diagnostics: `sudo zpool iostat -v kingdezignsnas 5 3`, `iostat -x 5 3`, `sudo dmesg -T | grep -i -E "ata|sd[b-f]|reset|error" | tail -30`, `top` (CPU), and `smartctl -A` CRC counts on all five disks (the MX500 sits on the eSATA/SATA-HAT path; watch for link resets or CRC growth).
### **After it finishes**
```bash
sudo zpool status kingdezignsnas
sudo zpool list -v kingdezignsnas
zfs list kingdezignsnas
sudo zpool scrub kingdezignsnas
```
Expected usable space: roughly 730 GiB free vs ~150 GiB before (estimates). Existing data keeps its old 2-data + 2-parity layout until rewritten; only new writes use the 3-data + 2-parity ratio. OpenZFS 2.4 provides `zfs rewrite` (`rewrite [-Prvx] [-o offset] [-l length] <directory|file ...>`) to re-lay-out existing data and reclaim the rest (~0.9 TiB free after a full rewrite). Considerations before using it: snapshots hold the old blocks, it needs free space as it works, it is heavy I/O (run it when Nextcloud is quiet and away from the Sunday 3:00 AM scrub and 2:30 AM sync), and take a current NAS16 backup first. Not yet run.
### **OMV note**
OMV reads pool size from ZFS, so it should show the larger capacity after completion. If the Storage / ZFS page still shows the old size, reload the page; verify with `zpool list` and `df -h` first.
---
## 🔒 Required Firewall Behavior
### **Inbound to NAS08**
@ -1026,7 +1081,8 @@ run of the script correctly reported "up to date."
- Outbound blocked to all VLANs except local + DNS responses.
- Critical infrastructure component for network‑wide DNS and storage.
- SSD hardening active: TRIM (weekly Wednesday 1AM), noatime (flashmemory plugin), SMART monitoring via weekly HTML email report.
- Five drives: 1x PNY CS900 500GB (OS), 4x Crucial BX500 1TB (data).
- Six drives: 1x PNY CS900 500GB (OS), 4x Crucial BX500 1TB (data) plus 1x Crucial MX500 1TB (data, added 2026-10-19).
- **ZFS pool `kingdezignsnas`** (OpenZFS 2.4.4) is a single RAIDZ2 vdev. On 2026-10-19 the MX500 was qualified (SMART short/long, full badblocks pass, 0 errors) and attached with `zpool attach kingdezignsnas raidz2-0 /dev/disk/by-id/ata-CT1000MX500SSD1_2415E8A6E7AC` (RAIDZ expansion, `feature@raidz_expansion` enabled). Expansion started 19:59 on 2026-10-19 and was ~36% done at 22.8 MB/s with ~27 h estimated on 2026-10-20 (initially ~5 h). Do not reboot NAS08 until it completes; new space appears only after completion; run a scrub afterward; `zfs rewrite` can later reclaim old-layout overhead. See the ZFS Pool section.
- **Shared permissions:** `ncshare` group (GID 1001) shared by `www-data` and `rufusking` — allows both Nextcloud and NFS to read/write the same files.
- NFS exports use `all_squash,anonuid=33,anongid=1001` — all NFS uploads land as `www-data:ncshare` automatically.
- Default ACLs on `/export/kingdezigns-public` ensure all new files/folders inherit `ncshare` group permissions.

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@ Hostname: **plex32**
IP Address: **192.168.150.45**
VLAN: **50 — Lab / Servers**
Last Updated: 2026-08-19
Last Updated: 2026-09-03
---
@ -23,17 +23,19 @@ This device is the **single Plex Media Server** for the KingDezigns network and
- Intel Celeron J4105 — 1.50GHz (4 cores) — Intel Quick Sync supported
- 8GB RAM
- 32GB eMMC (OS drive — no SMART support, health monitored via filesystem)
- 240GB External USB SSD (Plex config & transcode scratch)
- Gigabit Ethernet
### **Storage**
| Device | Type | Capacity | Role |
|--------|------|----------|------|
| mmcblk0 | eMMC | 29.1GB | OS / system drive |
| /dev/sda2 (`/mnt/external_ssd`) | USB SSD | 238GB | Local Plex config & transcode scratch storage |
| /mnt/plex/config | NFS (NAS08) | — | Plex config backup destination only — not used by container |
| /mnt/plex/transcode | NFS (NAS08) | — | Transcode scratch (local at /opt/plex/transcode) |
| /mnt/plex/transcode | NFS (NAS08) | — | Legacy NFS transcode entry (active transcode local at `/mnt/external_ssd/plex/transcode`) |
| /mnt/plex/media | NFS (NAS08) | 1.8TB | Media library |
> Note: Plex config and transcode directories are stored **locally** at `/opt/plex/` — not on NFS. The NFS config mount (`/mnt/plex/config`) is used as the backup destination by `plex32_backup.sh`. Only the media library is actively used by the container.
> Note: Plex config and transcode directories are stored **locally** on the external SSD at `/mnt/external_ssd/plex/` — offloading storage write cycles from the internal eMMC. The NFS config mount (`/mnt/plex/config`) is used as the backup destination by `plex32_backup.sh`. Only the media library is actively used by the container via NFS.
---
@ -81,9 +83,7 @@ This placement ensures:
## 🐳 Docker Configuration
### **Compose File Location**
```
~/docker/plex/docker-compose.yml
```
`/home/rufusking/docker/plex/docker-compose.yml`
### **Compose Contents**
```yaml
@ -103,8 +103,8 @@ services:
- "44"
- "993"
volumes:
- /opt/plex/config:/config
- /opt/plex/transcode:/transcode
- /mnt/external_ssd/plex/config:/config
- /mnt/external_ssd/plex/transcode:/transcode
- /mnt/plex/media:/media
restart: unless-stopped
@ -196,17 +196,20 @@ Uses same Zoho SMTP credentials as all other KingDezigns email alerts:
---
## 📁 NFS Mounts
## 📁 Mounts & Storage Configuration
Configured in `/etc/fstab` — mounts automatically on boot:
```
### **FSTAB Configuration (`/etc/fstab`)**
```text
192.168.150.35:/export/kingdezigns-all/Docker/plex/config /mnt/plex/config nfs defaults,_netdev 0 0
192.168.150.35:/export/kingdezigns-all/Docker/plex/transcode /mnt/plex/transcode nfs defaults,_netdev 0 0
192.168.150.35:/export/kingdezigns-public /mnt/plex/media nfs defaults,_netdev 0 0
# External USB SSD - Dedicated Plex Data Drive
UUID=463eb922-e181-43b1-a90d-cc5241701d69 /mnt/external_ssd ext4 defaults,nofail,x-systemd.device-timeout=5s 0 2
```
> Note: `/mnt/plex/config` is used by `plex32_backup.sh` as the backup destination — not by the Plex container. `/mnt/plex/transcode` exists in fstab but Plex uses the local `/opt/plex/transcode` directory instead.
> **Safeguard Notes on External SSD:**
> The USB SSD uses `nofail` and `x-systemd.device-timeout=5s`. If the external drive fails or is physically disconnected, the host system will still boot cleanly within 5 seconds without locking up or becoming inoperable.
---
@ -348,12 +351,12 @@ cd ~/docker/plex && docker compose down
# 2. Copy archive from NAS08
cp /mnt/plex/config/backups/plex/plex-config-YYYY-MM-DD.tar.gz /tmp/
# 3. Clear current config
sudo rm -rf /opt/plex/config/Library
# 3. Clear current config on external SSD
sudo rm -rf /mnt/external_ssd/plex/config/*
# 4. Extract backup
sudo tar -xzf /tmp/plex-config-YYYY-MM-DD.tar.gz -C /opt/plex
sudo chown -R rufusking:ncshare /opt/plex/config
sudo tar -xzf /tmp/plex-config-YYYY-MM-DD.tar.gz -C /mnt/external_ssd/plex/
sudo chown -R rufusking:ncshare /mnt/external_ssd/plex/config
# 5. Restart containers
cd ~/docker/plex && docker compose up -d
@ -361,7 +364,7 @@ cd ~/docker/plex && docker compose up -d
# 6. Verify
docker ps
# Both plex and tautulli should show Up
# Open http://192.168.150.45:32400/web and confirm library and watch history intact
# Open [http://192.168.150.45:32400/web](http://192.168.150.45:32400/web) and confirm library and watch history intact
# 7. Cleanup
rm /tmp/plex-config-YYYY-MM-DD.tar.gz
@ -464,11 +467,11 @@ Resolved — verified with a manual run; each issue now renders as one complete
## 🧠 Summary for AI Systems
- PLEX32 = **dedicated Plex Media Server + Tautulli** on VLAN 50 at 192.168.150.45.
- Runs on Dell Wyse 5070 (Celeron J4105, 8GB RAM, 32GB eMMC).
- Runs on Dell Wyse 5070 (Celeron J4105, 8GB RAM, 32GB eMMC OS drive + 240GB External USB SSD).
- Plex and Tautulli run as Docker containers via `~/docker/plex/docker-compose.yml`.
- **External USB SSD Mounted safely at `/mnt/external_ssd`** using `nofail,x-systemd.device-timeout=5s` — holds local Plex config (`/mnt/external_ssd/plex/config`) and transcode scratch space (`/mnt/external_ssd/plex/transcode`). Prevents eMMC wear and expanded root drive space to ~19GB free.
- **Intel Quick Sync hardware transcoding active** — requires `/dev/dri` device passthrough and `group_add: ["44","993"]` in compose. Without group_add, Plex silently falls back to software transcoding.
- **Lifetime Plex Pass** active — Sonic Radio, hardware transcoding, all Plex Pass features enabled.
- Config and transcode stored **locally** at `/opt/plex/` — not on NFS.
- Media library mounted from NAS08 via NFS at `/mnt/plex/media`.
- `/mnt/plex/config` NFS mount used as backup destination only — not by Plex container.
- Library is ~75% HEVC Main 10, ~25% H.264, 100% AAC audio — audio never transcodes.
@ -495,9 +498,8 @@ Resolved — verified with a manual run; each issue now renders as one complete
- **`plex32_health_report.sh` fixed 2026-07-12** — fixed the "Issues Detected" email block rendering each word on its own line, caused by a multi-character `IFS='. '` split; issues are now newline-delimited and read back with a `while read` loop.
- **`plex32_update_check.sh` updated 2026-08-18** — replaced heavy `docker pull` layer downloads with `skopeo inspect` for fast manifest digest comparisons. Adjusted Step 5 logic to prioritize "Updates Available" blue banner over non-fatal script check warnings.
- **Systemd override for Docker added 2026-08-19** — added `/etc/systemd/system/docker.service.d/override.conf` with `After=network-online.target remote-fs.target` and `Wants=network-online.target remote-fs.target` so Docker waits for NFS mounts on boot before starting containers.
---
# ✔️ End of File
---
### **Systemd Startup / NFS Dependency Fix (2026-08-19)**
After a system reboot at 8:53 AM, Plex failed to auto-start despite having `restart: unless-stopped` in `docker-compose.yml`.
@ -515,3 +517,6 @@ After a system reboot at 8:53 AM, Plex failed to auto-start despite having `rest
- Verified drop-in file is actively picked up by `docker.service`.
Resolved — Docker will now delay container startup on boot until network mounts are fully established.
# ✔️ End of File

192
server_umami.md Normal file
View file

@ -0,0 +1,192 @@
# Umami — Self-Hosted Web Analytics
Device Type: **Docker Containers (hosted on NAS16)**
Containers: **umami**, **umami_db**
Hostname / URL: **stats.cutthecard.net**
IP Address: **192.168.150.40** (shares NAS16's host IP), host port **3001**
VLAN: **50 — Lab / Servers**
Last Updated: 2026-10-02
---
## 🧩 Role & Purpose
Umami is the **self-hosted, cookie-free web analytics service** for CutTheCard and other KingDezigns sites. It answers: which pages people open, how long they stay, where they come from, whether they scroll/read articles, and which content they favor.
**Why Umami (decision record, 2026-10-01):**
- **Not Google Analytics** — CutTheCard handles financial data and trades on privacy; GA would put a third party's script on the site, force Privacy Statement changes and likely a consent banner, and contradicts the self-hosted philosophy used elsewhere (DNS, Git, proxy, stock API).
- **Not Plausible Community Edition** — needs ClickHouse as well as Postgres; too heavy for a Raspberry Pi already running Forgejo, Fund Tracker (x2), CutTheCard (x2) and Apache.
- **Umami** — one app container plus a Postgres 16 container (same pattern as Fund Tracker/CutTheCard), official ARM64 image (confirmed working on NAS16), no cookies, data stays on KingDezigns hardware.
- Google Search Console (no script on the site) is still recommended alongside it for search-query data.
---
## 🌐 Public Access
- **Domain:** `https://stats.cutthecard.net/`
- **Proxy:** NPM on HAS (192.168.150.30) → `192.168.150.40:3001` (scheme `http`)
- **NPM settings:** Let's Encrypt cert, **Force SSL** + **HTTP/2** on, Websockets **off** (not needed), Block Common Exploits on
- **Public DNS:** Dreamhost A record, kept current by the DDNS script on NAS16 (`/usr/scripts/ddns/ddns_update.sh` — `stats.cutthecard.net` was added to its subdomain list)
- **Pi-hole local DNS:** `stats.cutthecard.net` → `192.168.150.30` (avoids the NAT-hairpin failure; after editing Pi-hole v6 records use `docker restart pihole`, not `reloaddns`)
- **Tracker script URL:** `https://stats.cutthecard.net/insights` (renamed from the default `script.js` via `TRACKER_SCRIPT_NAME=insights`, so generic ad-block lists are less likely to match)
CrowdSec/Fail2Ban need no changes — traffic proxied through NPM inherits protection like every other service. No firewall changes were required (existing NPM → NAS16 inbound path).
---
## 🐳 Docker Configuration
### Project
OMV → Services → Compose, project/file name `umami`, at `/Kingdezignsnas16/umami/` (root-only directory; use `sudo bash -c "cd ... && ..."`).
| Item | Value |
|---|---|
| Compose file | `/Kingdezignsnas16/umami/umami.yml` (OMV-managed, symlinked as `compose.yml`) |
| Database data | `/opt/umami/pgdata` — owned `70:70` (postgres alpine UID/GID), mode `700` |
| Secrets file | `/opt/umami/umami.secrets` — **outside OMV's control**, `root:root`, mode `600` |
| App image | `ghcr.io/umami-software/umami:postgresql-latest` (ARM64 confirmed working) |
| DB image | `postgres:16-alpine` |
| Host port | `3001` → container `3000` (3000 on NAS16 is Forgejo) |
| Network | `umami_default` (created by compose) |
### Compose file (no secrets in it)
```yaml
services:
umami_db:
image: postgres:16-alpine
container_name: umami_db
restart: unless-stopped
env_file:
- /opt/umami/umami.secrets
environment:
- POSTGRES_DB=umami
- POSTGRES_USER=umami
volumes:
- /opt/umami/pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U umami -d umami"]
interval: 10s
timeout: 5s
retries: 5
umami:
image: ghcr.io/umami-software/umami:postgresql-latest
container_name: umami
restart: unless-stopped
depends_on:
umami_db:
condition: service_healthy
ports:
- "3001:3000"
env_file:
- /opt/umami/umami.secrets
environment:
- DISABLE_TELEMETRY=1
- TRACKER_SCRIPT_NAME=insights
```
### Secrets file — variable names only (values live in Vaultwarden and in the file itself)
```text
POSTGRES_PASSWORD=<secret>
DATABASE_URL=postgresql://umami:<same password>@umami_db:5432/umami
APP_SECRET=<secret>
```
Generate values with `openssl rand -hex 24` (hex avoids URL-encoding problems in `DATABASE_URL`). **Never write real values into documentation.** Changing the Postgres password after the database is initialized requires changing it inside Postgres too (the env var only applies on first init).
### Why `env_file` and not the OMV Environment box (lesson learned 2026-10-01)
- OMV **regenerates `umami.env` from its own stored settings** on every apply (the file carries a "do not edit, changes will be lost" header). Values typed into the file by hand are wiped, and the UI Environment box did not populate it in this setup. Compose therefore saw blank `${UMAMI_DB_PASSWORD}` and Postgres refused to start (`Database is uninitialized and superuser password is not specified`).
- Putting `UMAMI_DB_PASSWORD=...` in a *service's* `environment:` list does **not** fix `${...}` substitution — interpolation reads the project `.env`, not service environments.
- Fix: external `env_file` (above). Values go directly to each container, nothing depends on `umami.env`, and nothing is lost when OMV re-saves the project.
- Apply changes with **down then up** (not `docker restart`), which recreates containers with the new environment.
### Key commands
```bash
# Start / recreate
sudo bash -c "cd /Kingdezignsnas16/umami && docker compose down && docker compose up -d"
# Status / logs
sudo docker ps | grep umami
sudo docker logs umami --tail 30
sudo docker logs umami_db --tail 20
# Local health
curl -I http://192.168.150.40:3001 # expect 200
# Update images (both are real registry images, so pull is safe)
sudo bash -c "cd /Kingdezignsnas16/umami && docker compose pull && docker compose up -d"
```
---
## 📊 Websites Configured in Umami
| Website | Domain(s) | Notes |
|---|---|---|
| **CutTheCard** | `cutthecard.net`, `www.cutthecard.net` | Tracked via `/dashboard/site-scripts.js` (below). Website ID is embedded in that file; IDs are not secrets (visible in page source). |
| **kingdezigns.com** (personal site) | `kingdezigns.com`, `www.kingdezigns.com` | Separate Umami website with its own ID; tag added directly to that site's HTML, optionally with a copy of `reading-tracker.js`. |
Optional: a third website "CutTheCard QA" (its ID pasted into the `debt.qa.cutthecard.net` entry in `site-scripts.js`) would allow testing in QA without polluting production data. Not created yet.
---
## 🔌 How CutTheCard Loads Tracking
Full detail is in `server_debteliminator.md` §12h. Summary:
- Every public/app page carries **one** tag: `<script defer src="/dashboard/site-scripts.js?v=1"></script>`.
- `site-scripts.js` is the single registry of site-wide scripts. It loads Umami (page views, duration, referrers) and, on pages containing an `<article>`, `reading-tracker.js`.
- Custom events from `reading-tracker.js`: `scroll-depth` (25/50/75/100), `engaged-time` (30/60/120/180 s of active time), `article-read` (≥75% depth + ≥45 s active).
- CTA clicks can be tracked with `data-umami-event="..."` attributes on links — no JavaScript needed.
- Guards: admin area never tracked; only production hostnames report; Do Not Track and Global Privacy Control honored; Stripe-return pages have query/hash stripped; no `identify()` and no user data in event properties.
---
## 🔐 Security & Privacy
- **Default login is `admin` / `umami` — it must be changed on first login** (Settings → Profile), with the new password stored in Vaultwarden. Umami has no built-in 2FA or lockout; use a long random password.
- Tracking is cookie-free and first-party. Inside the logged-in app it is **page-level only** (no user identity, no financial data).
- The Privacy Statement should disclose the analytics (see open items); legal wording should be reviewed, and publishing a new version triggers the re-acceptance gate for all users.
- Your own visits can be excluded per browser per site: `localStorage.setItem('umami.disabled', 1)` on that site's origin.
---
## 💾 Backup
- Data to protect: `/opt/umami/pgdata` and `/opt/umami/umami.secrets`.
- Use `pg_dump`, not a raw copy of a live Postgres directory:
```bash
sudo docker exec umami_db pg_dump -U umami umami | gzip > /tmp/umami-$(date +%Y%m%d).sql.gz
```
- **Status (2026-10-02): not yet folded into `/usr/scripts/omv/nas16-backup.sh`** — see open items.
---
## 🛠️ Troubleshooting & Gotchas
| Symptom | Cause / Fix |
|---|---|
| `umami_db` unhealthy, log says superuser password not specified | Secrets not reaching the container — see "Why env_file" above. |
| `WARN The "UMAMI_DB_PASSWORD" variable is not set` | Compose still using `${...}` from an empty `umami.env`; use the `env_file` version of the compose file. |
| Chrome prompt "kingdezigns.com wants to access other devices on your local network" | Chrome Local Network Access. On the LAN, Pi-hole resolves `stats.cutthecard.net` to a private IP, and a **public** site loading a script from a private address triggers the prompt. Affects only the admin's own LAN browsers; real visitors resolve the public IP. Click Allow (remembered per site). |
| Tracker never sends data | Script `src` must be `https://` (an `http://` URL is blocked as mixed content on HTTPS pages); `data-domains` must be plain text matching the page's hostname (a copied markdown-link artifact like `[www.x.com](https://www.x.com)` breaks it); check `umami.disabled` in localStorage. |
| `dig: command not found` on NAS16 | Not installed; use `getent hosts stats.cutthecard.net` or `sudo apt install dnsutils`. |
| Pageviews appear but no Events | Events fire only on pages containing an `<article>` (blog posts and the six Learning Center guides), after scrolling/active time; confirm `reading-tracker.js` returns 200 in production; use Umami → Realtime to watch live. |
| `apply_site_scripts.py` crashes with PermissionError on `main.py` | The project directory is root-only; run the script with `sudo` (a dry run needs it too). |
---
## ⏳ Open Items (2026-10-02)
1. **Verify custom events in production** — page views confirmed recording; `scroll-depth` / `engaged-time` / `article-read` not yet confirmed visible in Events (tracker logic passed simulated testing; check production file availability and test on a single article page).
2. Confirm the default `admin` password was changed and stored in Vaultwarden.
3. Add `/opt/umami/pgdata` (via `pg_dump`) and `/opt/umami/umami.secrets` to `nas16-backup.sh`.
4. Update the Privacy Statement to disclose first-party, cookie-free analytics (including page-level tracking inside the app); legal review; bundle with another legal version bump if possible.
5. Optional: create a QA website in Umami and paste its ID into `site-scripts.js`.
6. Tag the in-flight external demo page(s) if they should be tracked (`apply_site_scripts.py` accepts extra page paths).
7. Consider CTA click events (`data-umami-event`) for planner/signup funnel measurement.
---
## 🧠 Summary for AI Systems
- Umami = **self-hosted, cookie-free analytics** on NAS16 (VLAN 50): containers `umami` (port 3001→3000) and `umami_db` (Postgres 16), OMV Compose project `umami` at `/Kingdezignsnas16/umami/`, public URL `https://stats.cutthecard.net` via NPM on HAS (Force SSL). Tracker script path is `/insights`.
- **Secrets are in `/opt/umami/umami.secrets` (outside OMV) via `env_file`** — OMV regenerates `umami.env` and wipes manual edits; `${VAR}` interpolation does not read service `environment:` entries. Never document secret values.
- Chosen over Google Analytics (privacy/trust/self-hosting philosophy) and Plausible CE (ClickHouse too heavy for the Pi).
- CutTheCard loads tracking through **one** loader (`/dashboard/site-scripts.js`); future scripts are added there only. See `server_debteliminator.md` §12h.
- Two Umami websites: CutTheCard and the personal kingdezigns.com site.
- Pi-hole override `stats.cutthecard.net → 192.168.150.30`; DDNS script updated; the Chrome Local Network Access prompt on LAN-side public sites is expected and harmless.
- Default login must be changed; backup is **not yet** in `nas16-backup.sh`; custom reading events were not yet confirmed at time of writing.
---
# ✔️ End of File

View file

@ -1,7 +1,7 @@
# VLAN 1 — Infrastructure / Default Network
Subnet: **192.168.100.0/24**
Last Updated: 2026-05-21
Last Updated: 2026-09-15
---
@ -31,6 +31,7 @@ This network remains active during ongoing migration and should not be aggressiv
- Switches & access points
- Emergency recovery access
- At least one wired management workstation
- **KingDezigns-AI-001** (added 2026-09-14) — GMKtec NucBox K8 Plus running Ollama + OpenCode (local AI coding agent). Static reservations `192.168.100.50` / `192.168.100.51`. See `kingdezigns-ai-001-summary.md` and the note below.
---
@ -61,6 +62,13 @@ This network remains active during ongoing migration and should not be aggressiv
- Infrastructure remains on VLAN 1 during migration.
- Avoid strict firewall enforcement until migration is complete.
- Maintain at least one wired management workstation for safety.
- **KingDezigns-AI-001's OpenCode web UI (port 4096) currently has no
server password set** (`OPENCODE_SERVER_PASSWORD` unset) — any device
that can reach `192.168.100.50:4096` / `.51:4096` can create files and
run shell commands on that host with no authentication. Accepted for
now as a trusted-home-LAN convenience, but **port 4096 must never be
port-forwarded to the internet**, and setting a server password is a
recommended follow-up. See `kingdezigns-ai-001-summary.md`.
---
@ -72,6 +80,12 @@ This network remains active during ongoing migration and should not be aggressiv
- Guest VLAN 40 behavior depends on default policy.
- All VLANs may send DNS to Pi‑hole in VLAN 50.
- VLAN 1 is a reachable core network but protected from lower‑trust zones.
- **KingDezigns-AI-001** (192.168.100.50/.51) is a local AI coding
workstation on this VLAN — Ollama (loopback-only, `127.0.0.1:11434`)
+ OpenCode (LAN-exposed web UI, port 4096, currently **no server
password**). Not the same machine as KingDezigns001 (VLAN 20 admin
workstation). See `kingdezigns-ai-001-summary.md` and
`network_index.md`.
---