Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-1996]): rework Morse Tree reference into a computed connector-line layout
Adam Eivyfd6a3b369a39
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f618028724..e392bdfad0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -24,6 +24,7 @@- **[issue-1988] POST History is now a responsive analytics dashboard.** The History view (`client/src/components/meatspace/post/PostHistory.jsx`) was a single `max-w-3xl` column that stacked a lone overall-score line chart, a 3-up stat block, and the session table — surfacing only a fraction of what `getPostStats` already computes. It now fills desktop width and surfaces the full stats payload: a 4-up summary of **Sessions / Avg Score / Current Streak / Longest Streak**, a wide **Score Trend** line beside a horizontal **Avg by Domain** bar chart (each domain colored to match its `text-*-400` domain class), and a **Drill Breakdown** card that groups every drill's average into per-domain progress bars — so per-domain and per-drill averages plus streaks are visible without opening a single session. The five training domains (Mental Math / Memory / Wordplay / Verbal Agility / Imagination) are derived from each drill's *type* via `DRILL_TO_DOMAIN`, because the runners persist coarse module keys (`mental-math`, `llm-drills`) rather than domain keys — so all LLM drills split correctly across Wordplay/Verbal/Imagination instead of collapsing into one bucket. Mobile stays single-column; the 7/30/90/All range selector still drives every panel from one fetch. (Closes #1988)- **[issue-1989] POST Memory surfaces are now responsive.** The Memory Builder, Practice, and Session Results screens were all pinned to a single narrow `max-w-2xl` column that wasted desktop width. **Memory Builder** (`MemoryBuilder.jsx`) now renders its saved items as a responsive card grid (`grid-cols-1 md:grid-cols-2 xl:grid-cols-3`) — each card lays out the item icon, title, line/chunk meta, and mastery badge above a full-width Practice button (with an aria-labeled delete for non-built-ins), while the create form and description stay in a readable `max-w-2xl` column above the grid. **Memory Practice** (`MemoryPractice.jsx`) widens the reading-oriented screens to `max-w-4xl` — the practice-mode picker (now a two-column card grid), Learn progressive-reveal, and Speed Run — while the active-recall focus steps (Sequence, Fill-in-the-Blank, Spaced Repetition) stay at a comfortable `max-w-2xl` for readability. **Session Results** (`PostSessionResults.jsx`) widens to `max-w-4xl` and lays the per-drill breakdown out in two columns on desktop. Layout-only: create/edit/delete, practice submission, mastery display, and score/breakdown rendering are unchanged; every surface collapses to a single column on mobile. (Closes #1989)- **[issue-1995] POST Morse modes and reference tabs are now deep-linkable via the URL.** The Morse trainer kept its mode (Copy/Send) and reference view (Tree/Length/List) in local `useState`, so — unlike every other routed POST sub-page — those views weren't bookmarkable, shareable, reload-safe, or reachable from ⌘K / voice. The selected mode now lives in the `/post/morse/:mode` route segment (Copy → `/post/morse/copy`, Send → `/post/morse/send`) and the reference tab in a `?ref=tree|length|list` search param (via the shared `useDrawerTab` hook) — so the exact drill + reference you're looking at is the single source of truth in the URL and survives reload/share. A stale or deleted deep link degrades gracefully: an unknown `:mode` segment falls back to the mode-picker grid (not a blank panel) and an unknown `?ref` value falls back to the Tree view. New `NAV_COMMANDS` entries (`nav.post.morse.copy` / `.send` / `.tree` / `.length` / `.list`) make "morse send", "morse tree", etc. reachable from the ⌘K palette and voice navigation. (`client/src/components/meatspace/post/MorseTrainer.jsx`, `client/src/components/meatspace/tabs/PostTab.jsx`, `server/lib/navManifest.js`, Closes #1995)+- **[issue-1996] The Morse Tree reference view is now a clear, fully-labeled tree.** The Tree reference previously gave every branch equal-width columns — including missing ones — so a lightly-populated side of the tree could squeeze and visually displace everything above it, making the start node appear to sit under the "dit" side and making some letters (especially E and its descendants) hard to find. The tree now computes each node's position from its actual subtree size and draws it with connector lines, so the start node sits centered under "Start," every one of the 41 characters (A–Z, 0–9, and punctuation) is visible and labeled, and the live keying highlight during a Send drill only lights up a node once you've actually keyed to it.- **[issue-1991] POST memory items now resurface on a spaced-repetition schedule.** Memory items (songs, poems, speeches, sequences) tracked mastery but had no review cadence — practice was entirely user-initiated, with nothing telling you *what to review today*. Each item now carries a lightweight SM-2-inspired schedule (ease, interval, next-review date): finishing a practice session reschedules the item automatically — a strong, mostly-correct session pushes the next review further out, while a miss-heavy session resets it to "due now" so it comes back around immediately. The Memory Builder gains a **Due Today (N)** banner listing what's ready for review with a one-click **Review Next**, plus a small "Due" badge on each item that's ready; the count updates the moment you finish practicing. Existing items keep working unchanged — a migration stamps every pre-existing item with a "due now" default so nothing gets stranded — and a new `GET /post/memory-items/due` endpoint lists due items most-overdue first.- **[issue-1992] Opt-in adaptive difficulty for mental-math POST drills.** Math drill params (`steps` / `maxDigits` / `maxExponent` / estimation `tolerancePct`) were fixed values from config that never responded to how you were doing. A new **Adaptive difficulty** toggle in the Drill Configuration screen (default OFF, so existing installs are unchanged) makes each math drill nudge its primary difficulty knob from your recent scored performance: sustained high accuracy (≥90% over enough sessions) bumps it one step harder, repeated misses (≤50%) ease it back, all clamped to safe min/max bounds — and it won't move until it has enough scored samples to trust. The adjustment is a pure, unit-tested policy (`server/lib/postAdaptive.js`) applied server-side at drill-generation time, so manual config still wins whenever Adaptive is off. It's fully transparent: each math drill card shows the effective difficulty (e.g. "Adaptive: max digits 2 → 3 (harder · 94% recent)") via a new `GET /post/adaptive-preview` endpoint, so it's never a black box. (`server/lib/postAdaptive.js`, `server/services/meatspacePost.js`, `client/src/components/meatspace/post/PostDrillConfig.jsx`, Closes #1992)- **[issue-1993] New deterministic cognitive drills — N-Back, Digit Span, and Stroop.** POST spanned math, LLM, and memory drills but was missing classic non-LLM cognitive-training exercises. A new **Cognitive** domain adds three provider-free drills: **N-Back** (1/2/3-back working-memory matching), **Digit Span** (forward/backward sequence recall), and **Stroop** (name the ink color, not the word — attention/inhibition). Each is configurable in the Drill Configuration screen, playable in both Test and Train modes via a dedicated interactive runner, scored, and saved to your training history alongside every other drill — with **zero AI provider calls**. Scoring is recomputed server-side from the generated drill (never trusting the client) using a shared 80% accuracy + 20% speed blend, and the drills are picked up by Full POST and Quick 5 Min automatically. (Closes #1993)diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsxindex ab6bd634f2..8928b63e80 100644--- a/client/src/components/meatspace/post/MorseTrainer.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.jsx@@ -2,7 +2,7 @@ import { useState, useEffect, useRef, useCallback } from 'react';import { ArrowLeft, Radio, Headphones, Hand, CheckCircle, XCircle, Play, RefreshCw, Volume2, GitBranch, List as ListIcon, Ruler, Eraser } from 'lucide-react';import useDrawerTab from '../../../hooks/useDrawerTab';-const MORSE_TABLE = {+export const MORSE_TABLE = {A: '.-', B: '-...', C: '-.-.', D: '-..', E: '.', F: '..-.',G: '--.', H: '....', I: '..', J: '.---', K: '-.-', L: '.-..',M: '--', N: '-.', O: '---', P: '.--.', Q: '--.-', R: '.-.',@@ -24,6 +24,8 @@ const MORSE_BY_LENGTH = MORSE_ENTRIES.reduce((acc, [ch, code]) => {// Binary tree: walk left for `-` (DAH), right for `.` (DIT). Each node's path// from the root spells its morse code; missing paths are nulls (e.g. `----`).+// Morse is timing-decoded rather than prefix-free, so a node can carry both a+// letter (e.g. E, T, A) AND have children for longer codes that extend it.const MORSE_TREE = (() => {const root = { char: '·', code: '', dah: null, dit: null };for (const [ch, code] of MORSE_ENTRIES) {@@ -38,6 +40,48 @@ const MORSE_TREE = (() => {return root;})();+// Tidy tree layout: true leaves (nodes with no dah/dit children) get+// sequential x-slots in left-to-right (dah-then-dit) order; every internal+// node's x is the midpoint of its children. This replaces nested equal-split+// `flex-1` divs — which gave a missing branch the same width as a populated+// one at every depth, so a lightly-populated subtree several levels down+// could visually squeeze/shift everything above it, including the root —+// with positions derived from each subtree's real size. The root always+// lands at the midpoint of its two top branches and every node keeps a+// stable, non-overlapping slot regardless of how deep/sparse its subtree is.+function layoutMorseTree(root) {+ const nodes = [];+ const edges = [];+ let nextLeafX = 0;++ function visit(node, depth) {+ if (!node) return null;+ let x;+ const dahPos = visit(node.dah, depth + 1);+ const ditPos = visit(node.dit, depth + 1);+ const childXs = [dahPos, ditPos].filter(Boolean).map((p) => p.x);+ if (childXs.length === 0) {+ x = nextLeafX;+ nextLeafX += 1;+ } else {+ x = childXs.reduce((a, b) => a + b, 0) / childXs.length;+ }+ if (dahPos) edges.push({ x1: x, y1: depth, x2: dahPos.x, y2: depth + 1, childCode: node.dah.code });+ if (ditPos) edges.push({ x1: x, y1: depth, x2: ditPos.x, y2: depth + 1, childCode: node.dit.code });+ const pos = { x, depth, node };+ nodes.push(pos);+ return pos;+ }++ visit(root, 0);+ const maxDepth = nodes.reduce((max, n) => Math.max(max, n.depth), 0);+ return { nodes, edges, width: Math.max(1, nextLeafX), maxDepth };+}++const MORSE_TREE_LAYOUT = layoutMorseTree(MORSE_TREE);+const TREE_SLOT_W = 26;+const TREE_ROW_H = 34;+const KOCH_ORDER = ['K', 'M', 'U', 'R', 'E', 'S', 'N', 'A', 'P', 'T', 'L', 'W', 'I', '.', 'J', 'Z', '=', 'F', 'O', 'Y', ',', 'V', 'G', '5', '/', 'Q', '9', '2', 'H', '3', '8', 'B', '?', '4', '7', 'C', '1', 'D', '6', '0', 'X'];const PREFS_KEY = 'portos-post-morse-prefs';@@ -491,36 +535,39 @@ function ReferenceWidget({ keying, mode }) {);}-function TreeNode({ node, currentPath }) {- if (!node) return <div className="flex-1" />;- const matched = !!node.char && currentPath === node.code;+function isNodeOnPath(node, currentPath) {+ // Root's placeholder char ('·') is truthy but isn't a real decoded+ // character — gate on `currentPath.length > 0` too so an idle/empty path+ // (reference-only view, or before the first key press) never lights up+ // the root as if it were the live-keyed match.+ const matched = !!node.char && currentPath.length > 0 && currentPath === node.code;const onPath = currentPath.length > 0 && currentPath.startsWith(node.code) && node.code !== currentPath;- const hasChildren = node.dah || node.dit;- const display = node.char || (node.code === '' ? '·' : '');+ return { matched, onPath };+}+function TreeNodeLabel({ x, depth, node, currentPath }) {+ const { matched, onPath } = isNodeOnPath(node, currentPath);+ const display = node.char || (node.code === '' ? '·' : '');return (- <div className="flex flex-col items-center min-w-0 flex-1">- <div- className={`text-[11px] font-mono px-1.5 py-0.5 rounded transition-colors ${- matched ? 'bg-port-accent text-white font-bold' :- onPath ? 'text-port-accent' :- display ? 'text-gray-300' : 'text-gray-700'- }`}- title={node.code || 'start'}- >- {display || '·'}- </div>- {hasChildren && (- <div className={`flex gap-0.5 mt-0.5 w-full border-t ${onPath || matched ? 'border-port-accent/40' : 'border-port-border'}`}>- <TreeNode node={node.dah} currentPath={currentPath} />- <TreeNode node={node.dit} currentPath={currentPath} />- </div>- )}+ <div+ className={`absolute -translate-x-1/2 -translate-y-1/2 whitespace-nowrap text-[11px] font-mono px-1.5 py-0.5 rounded transition-colors ${+ matched ? 'bg-port-accent text-white font-bold' :+ onPath ? 'text-port-accent bg-port-bg' :+ display ? 'text-gray-300 bg-port-bg' : 'text-gray-700 bg-port-bg'+ }`}+ style={{ left: x * TREE_SLOT_W + TREE_SLOT_W / 2, top: depth * TREE_ROW_H + TREE_ROW_H / 2 }}+ title={node.code || 'start'}+ >+ {display || '·'}</div>);}function TreeView({ currentPath, mode }) {+ const { nodes, edges, width, maxDepth } = MORSE_TREE_LAYOUT;+ const pixelWidth = width * TREE_SLOT_W;+ const pixelHeight = (maxDepth + 1) * TREE_ROW_H;+return (<div><div className="flex items-center justify-between text-[10px] uppercase tracking-wide text-gray-500 mb-2">@@ -529,8 +576,26 @@ function TreeView({ currentPath, mode }) {<span>dit →</span></div><div className="overflow-x-auto pb-1">- <div className="min-w-[36rem]">- <TreeNode node={MORSE_TREE} currentPath={currentPath} />+ <div className="relative mx-auto" style={{ width: pixelWidth, height: pixelHeight }}>+ <svg className="absolute inset-0 overflow-visible" width={pixelWidth} height={pixelHeight}>+ {edges.map((e, i) => {+ const highlighted = currentPath.length > 0 && currentPath.startsWith(e.childCode);+ return (+ <line+ key={i}+ x1={e.x1 * TREE_SLOT_W + TREE_SLOT_W / 2}+ y1={e.y1 * TREE_ROW_H + TREE_ROW_H / 2}+ x2={e.x2 * TREE_SLOT_W + TREE_SLOT_W / 2}+ y2={e.y2 * TREE_ROW_H + TREE_ROW_H / 2}+ className={highlighted ? 'stroke-port-accent' : 'stroke-port-border'}+ strokeWidth={highlighted ? 2 : 1}+ />+ );+ })}+ </svg>+ {nodes.map(({ x, depth, node }) => (+ <TreeNodeLabel key={node.code} x={x} depth={depth} node={node} currentPath={currentPath} />+ ))}</div></div><p className="text-[10px] text-gray-500 mt-3">diff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsxindex e248e258ab..5c835ace75 100644--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx@@ -1,7 +1,7 @@import { describe, it, expect, vi } from 'vitest';import { render, screen, fireEvent } from '@testing-library/react';import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom';-import MorseTrainer, { MODES, MORSE_MODE_IDS } from './MorseTrainer';+import MorseTrainer, { MODES, MORSE_MODE_IDS, MORSE_TABLE } from './MorseTrainer';// Surfaces the live URL (path + search) so tests can assert the reference tab// is encoded in the query string — the "URL is the source of truth" contract.@@ -64,3 +64,35 @@ describe('MorseTrainer deep-linking', () => {expect(screen.getByTestId('loc').textContent).toBe('/post/morse');});});++describe('MorseTrainer Tree reference view', () => {+ it('renders a labeled, reachable node for all 41 characters', () => {+ const { container } = renderMorse({ mode: null, onSelectMode: vi.fn() });+ // Every node (including the root) carries its own morse code (or 'start'+ // for the root) as its `title` — the most reliable way to pick each tree+ // node out individually, since letter text alone can collide with other+ // on-screen content (e.g. mode-card labels).+ const chars = Object.keys(MORSE_TABLE);+ for (const ch of chars) {+ const code = MORSE_TABLE[ch];+ const node = container.querySelector(`[title="${code}"]`);+ expect(node, `expected a tree node for "${ch}" (${code})`).toBeTruthy();+ expect(node.textContent).toBe(ch);+ }+ });++ it('centers the start node roughly under "start", not pinned to one edge', () => {+ const { container } = renderMorse({ mode: null, onSelectMode: vi.fn() });+ const root = container.querySelector('[title="start"]');+ expect(root).toBeTruthy();+ expect(root.textContent).toBe('·');+ // Regression guard for the reported bug: the root previously rendered+ // displaced toward the DIT side. Its computed x-slot should sit near the+ // horizontal middle of the tree's total width, not near either edge.+ const treeContainer = root.closest('.relative.mx-auto');+ const totalWidth = parseFloat(treeContainer.style.width);+ const rootLeft = parseFloat(root.style.left);+ expect(rootLeft).toBeGreaterThan(totalWidth * 0.3);+ expect(rootLeft).toBeLessThan(totalWidth * 0.7);+ });+});