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
feat: add MeatSpace health tracker with death clock and TSV import
Adam Eivyd68a15d2fefc
diff --git a/.changelog/v1.8.x.md b/.changelog/v1.8.x.mdnew file mode 100644index 0000000000..0c84432ec1--- /dev/null+++ b/.changelog/v1.8.x.md@@ -0,0 +1,22 @@+# Release v1.8.x - Changelog++Released: YYYY-MM-DD++## Overview++MeatSpace: Physical health dashboard with death clock countdown, LEV 2045 tracker, and health spreadsheet import.++## Features++### MeatSpace — Health Tracker & Death Clock (Phase 1)+- **New top-level MeatSpace page** (`/meatspace`) with 6 tabs: Overview, Alcohol, Blood & Body, Lifestyle, Nutrition, Import+- **Death Clock Countdown**: Live years/months/weeks/days/hours/minutes/seconds countdown to estimated death date, combining SSA actuarial baseline (78.5y) with genome-adjusted life expectancy from Digital Twin and lifestyle adjustment multipliers (smoking, alcohol, exercise, sleep, diet, stress, BMI)+- **LEV 2045 Tracker**: Longevity Escape Velocity progress visualization — research timeline progress bar, on-track/at-risk status, survival margin to age 66+- **TSV Spreadsheet Import**: Bulk import from 257-column health spreadsheet (3 header rows + 2 summary rows + daily data). Parses nutrition, alcohol (individual beverages with ABV/serving size), body composition, blood tests, DNA methylation (Elysium Index), and eye prescriptions. Idempotent — re-importing replaces all data+- **Automatic sex detection** from genome Y-chromosome SNP count (>1000 = male)+- **Lifestyle adjustment formula**: Additive years for 7 factors — smoking (0 to -10), alcohol (+0.5 to -5), exercise (+2 to -2), sleep (+1 to -1.5), diet (+2 to -3), stress (+1 to -2), BMI (+0.5 to -3)+- **Sidebar navigation**: MeatSpace collapsible section with alphabetically ordered children (Alcohol, Blood & Body, Import, Lifestyle, Nutrition, Overview)+- **Data model**: Sparse daily-log.json (nutrition, alcohol, body, mercury per day), blood-tests.json (with reference ranges), epigenetic-tests.json, eyes.json — all created on import+- New API endpoints: `GET /api/meatspace`, `GET/PUT /api/meatspace/config`, `PUT /api/meatspace/lifestyle`, `GET /api/meatspace/death-clock`, `GET /api/meatspace/lev`, `POST /api/meatspace/import/tsv`+- 24 new tests covering death clock math (lifestyle adjustments, SSA baseline fallback, negative adjustments, expired dates), LEV computation, and TSV import (date parsing, sorting, null handling, body composition, file output)+- Installed `recharts` charting library for future chart components (Phase 2+)diff --git a/client/package-lock.json b/client/package-lock.jsonindex b63bb788c5..91f2bf52af 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -24,6 +24,7 @@"react-hot-toast": "^2.6.0","react-markdown": "^10.1.0","react-router-dom": "^7.1.1",+ "recharts": "^3.7.0","socket.io-client": "^4.8.3","three": "^0.182.0"},@@ -1748,6 +1749,42 @@}}},+ "node_modules/@reduxjs/toolkit": {+ "version": "2.11.2",+ "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.11.2.tgz",+ "integrity": "sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ==",+ "license": "MIT",+ "dependencies": {+ "@standard-schema/spec": "^1.0.0",+ "@standard-schema/utils": "^0.3.0",+ "immer": "^11.0.0",+ "redux": "^5.0.1",+ "redux-thunk": "^3.1.0",+ "reselect": "^5.1.0"+ },+ "peerDependencies": {+ "react": "^16.9.0 || ^17.0.0 || ^18 || ^19",+ "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ },+ "react-redux": {+ "optional": true+ }+ }+ },+ "node_modules/@reduxjs/toolkit/node_modules/immer": {+ "version": "11.1.4",+ "resolved": "https://registry.npmjs.org/immer/-/immer-11.1.4.tgz",+ "integrity": "sha512-XREFCPo6ksxVzP4E0ekD5aMdf8WMwmdNaz6vuvxgI40UaEiu6q3p8X52aU6GdyvLY3XXX/8R7JOTXStz/nBbRw==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/immer"+ }+ },"node_modules/@rolldown/pluginutils": {"version": "1.0.0-beta.27","resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",@@ -2069,6 +2106,18 @@"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==","license": "MIT"},+ "node_modules/@standard-schema/spec": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",+ "license": "MIT"+ },+ "node_modules/@standard-schema/utils": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",+ "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",+ "license": "MIT"+ },"node_modules/@swc/helpers": {"version": "0.5.15","resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz",@@ -2129,6 +2178,69 @@"@babel/types": "^7.28.2"}},+ "node_modules/@types/d3-array": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",+ "license": "MIT"+ },+ "node_modules/@types/d3-color": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",+ "license": "MIT"+ },+ "node_modules/@types/d3-ease": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",+ "license": "MIT"+ },+ "node_modules/@types/d3-interpolate": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-color": "*"+ }+ },+ "node_modules/@types/d3-path": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",+ "license": "MIT"+ },+ "node_modules/@types/d3-scale": {+ "version": "4.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-time": "*"+ }+ },+ "node_modules/@types/d3-shape": {+ "version": "3.1.8",+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",+ "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-path": "*"+ }+ },+ "node_modules/@types/d3-time": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",+ "license": "MIT"+ },+ "node_modules/@types/d3-timer": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",+ "license": "MIT"+ },"node_modules/@types/debug": {"version": "4.1.12","resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",@@ -2236,6 +2348,12 @@"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==","license": "MIT"},+ "node_modules/@types/use-sync-external-store": {+ "version": "0.0.6",+ "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",+ "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",+ "license": "MIT"+ },"node_modules/@types/webxr": {"version": "0.5.24","resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",@@ -2645,6 +2763,15 @@"integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==","license": "MIT"},+ "node_modules/clsx": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/comma-separated-tokens": {"version": "2.0.3","resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",@@ -2737,6 +2864,127 @@"license": "MIT","peer": true},+ "node_modules/d3-array": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",+ "license": "ISC",+ "dependencies": {+ "internmap": "1 - 2"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-color": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-ease": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-format": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",+ "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-interpolate": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-path": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-scale": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2.10.0 - 3",+ "d3-format": "1 - 3",+ "d3-interpolate": "1.2.0 - 3",+ "d3-time": "2.1.1 - 3",+ "d3-time-format": "2 - 4"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-shape": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",+ "license": "ISC",+ "dependencies": {+ "d3-path": "^3.1.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-time-format": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",+ "license": "ISC",+ "dependencies": {+ "d3-time": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -2754,6 +3002,12 @@}}},+ "node_modules/decimal.js-light": {+ "version": "2.5.1",+ "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",+ "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",+ "license": "MIT"+ },"node_modules/decode-named-character-reference": {"version": "1.3.0","resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",@@ -2857,6 +3111,16 @@"node": ">=10.0.0"}},+ "node_modules/es-toolkit": {+ "version": "1.44.0",+ "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.44.0.tgz",+ "integrity": "sha512-6penXeZalaV88MM3cGkFZZfOoLGWshWWfdy0tWw/RlVVyhvMaWSBTOvXNeiW3e5FwdS5ePW0LGEu17zT139ktg==",+ "license": "MIT",+ "workspaces": [+ "docs",+ "benchmarks"+ ]+ },"node_modules/esbuild": {"version": "0.25.12","resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",@@ -2919,6 +3183,12 @@"url": "https://opencollective.com/unified"}},+ "node_modules/eventemitter3": {+ "version": "5.0.4",+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",+ "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",+ "license": "MIT"+ },"node_modules/extend": {"version": "3.0.2","resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",@@ -3165,12 +3435,32 @@"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==","license": "MIT"},+ "node_modules/immer": {+ "version": "10.2.0",+ "resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz",+ "integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==",+ "license": "MIT",+ "peer": true,+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/immer"+ }+ },"node_modules/inline-style-parser": {"version": "0.2.7","resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz","integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==","license": "MIT"},+ "node_modules/internmap": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/is-alphabetical": {"version": "2.0.1","resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",@@ -4594,7 +4884,8 @@"version": "16.13.1","resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz","integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/react-markdown": {"version": "10.1.0",@@ -4648,6 +4939,30 @@"loose-envify": "^1.1.0"}},+ "node_modules/react-redux": {+ "version": "9.2.0",+ "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",+ "integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/use-sync-external-store": "^0.0.6",+ "use-sync-external-store": "^1.4.0"+ },+ "peerDependencies": {+ "@types/react": "^18.2.25 || ^19",+ "react": "^18.0 || ^19",+ "redux": "^5.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "redux": {+ "optional": true+ }+ }+ },"node_modules/react-refresh": {"version": "0.17.0","resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",@@ -4734,6 +5049,52 @@"node": ">=8.10.0"}},+ "node_modules/recharts": {+ "version": "3.7.0",+ "resolved": "https://registry.npmjs.org/recharts/-/recharts-3.7.0.tgz",+ "integrity": "sha512-l2VCsy3XXeraxIID9fx23eCb6iCBsxUQDnE8tWm6DFdszVAO7WVY/ChAD9wVit01y6B2PMupYiMmQwhgPHc9Ew==",+ "license": "MIT",+ "workspaces": [+ "www"+ ],+ "dependencies": {+ "@reduxjs/toolkit": "1.x.x || 2.x.x",+ "clsx": "^2.1.1",+ "decimal.js-light": "^2.5.1",+ "es-toolkit": "^1.39.3",+ "eventemitter3": "^5.0.1",+ "immer": "^10.1.1",+ "react-redux": "8.x.x || 9.x.x",+ "reselect": "5.1.1",+ "tiny-invariant": "^1.3.3",+ "use-sync-external-store": "^1.2.2",+ "victory-vendor": "^37.0.2"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/redux": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",+ "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/redux-thunk": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",+ "integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",+ "license": "MIT",+ "peerDependencies": {+ "redux": "^5.0.0"+ }+ },"node_modules/remark-parse": {"version": "11.0.0","resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",@@ -4776,6 +5137,12 @@"node": ">=0.10.0"}},+ "node_modules/reselect": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",+ "integrity": "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==",+ "license": "MIT"+ },"node_modules/resolve": {"version": "1.22.11","resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",@@ -5252,6 +5619,12 @@"integrity": "sha512-IQrh3lEPM93wVCEczc9SaAOvkmcoQn/G8Bo1e8ZPlY3X3bnAxWaBdvTdvM1hP62iZp0BXWDy4vTAy4fF0+Dlpg==","license": "MIT"},+ "node_modules/tiny-invariant": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",+ "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",+ "license": "MIT"+ },"node_modules/tinyglobby": {"version": "0.2.15","resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",@@ -5585,6 +5958,28 @@"url": "https://opencollective.com/unified"}},+ "node_modules/victory-vendor": {+ "version": "37.3.6",+ "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",+ "integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==",+ "license": "MIT AND ISC",+ "dependencies": {+ "@types/d3-array": "^3.0.3",+ "@types/d3-ease": "^3.0.0",+ "@types/d3-interpolate": "^3.0.1",+ "@types/d3-scale": "^4.0.2",+ "@types/d3-shape": "^3.1.0",+ "@types/d3-time": "^3.0.0",+ "@types/d3-timer": "^3.0.0",+ "d3-array": "^3.1.6",+ "d3-ease": "^3.0.1",+ "d3-interpolate": "^3.0.1",+ "d3-scale": "^4.0.2",+ "d3-shape": "^3.1.0",+ "d3-time": "^3.0.0",+ "d3-timer": "^3.0.1"+ }+ },"node_modules/vite": {"version": "6.4.1","resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz",diff --git a/client/package.json b/client/package.jsonindex 7712a01f40..7be5afd223 100644--- a/client/package.json+++ b/client/package.json@@ -25,6 +25,7 @@"react-hot-toast": "^2.6.0","react-markdown": "^10.1.0","react-router-dom": "^7.1.1",+ "recharts": "^3.7.0","socket.io-client": "^4.8.3","three": "^0.182.0"},diff --git a/client/src/App.jsx b/client/src/App.jsxindex b8f07be55f..f8b4ee9dc1 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -17,6 +17,7 @@ import Shell from './pages/Shell';import BrowserPage from './pages/Browser';import Jira from './pages/Jira';import Instances from './pages/Instances';+import MeatSpace from './pages/MeatSpace';// Lazy load heavier pages for code splitting// DevTools pages are large (~2300 lines total) so lazy load them@@ -67,6 +68,8 @@ export default function App() {<Route path="shell" element={<Shell />} /><Route path="browser" element={<BrowserPage />} /><Route path="instances" element={<Instances />} />+ <Route path="meatspace" element={<Navigate to="/meatspace/overview" replace />} />+ <Route path="meatspace/:tab" element={<MeatSpace />} /><Route path="jira" element={<Navigate to="/devtools/jira" replace />} /><Route path="devtools/jira" element={<Jira />} /><Route path="city" element={<CyberCity />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 4202bdd294..23593a5be5 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -44,7 +44,10 @@ import {Building2,Ticket,Network,- Flame+ Flame,+ Skull,+ HeartPulse,+ ClipboardList} from 'lucide-react';import packageJson from '../../package.json';import Logo from './Logo';@@ -123,6 +126,18 @@ const navItems = []},{ to: '/instances', label: 'Instances', icon: Network, single: true },+ {+ label: 'MeatSpace',+ icon: Skull,+ children: [+ { to: '/meatspace/alcohol', label: 'Alcohol', icon: Activity },+ { to: '/meatspace/blood', label: 'Blood & Body', icon: HeartPulse },+ { to: '/meatspace/import', label: 'Import', icon: Upload },+ { to: '/meatspace/lifestyle', label: 'Lifestyle', icon: ClipboardList },+ { to: '/meatspace/nutrition', label: 'Nutrition', icon: Flame },+ { to: '/meatspace/overview', label: 'Overview', icon: Activity }+ ]+ },{ to: '/security', label: 'Security', icon: Camera, single: true },{ to: '/shell', label: 'Shell', icon: SquareTerminal, single: true },{ to: '/agents', label: 'Social Agents', icon: Users, single: true },@@ -512,6 +527,7 @@ export default function Layout() {const isFullWidth = location.pathname.startsWith('/cos') ||location.pathname.startsWith('/brain') ||location.pathname.startsWith('/digital-twin') ||+ location.pathname.startsWith('/meatspace') ||location.pathname.startsWith('/agents') ||location.pathname === '/shell' ||location.pathname.startsWith('/city');diff --git a/client/src/components/meatspace/DeathClockCountdown.jsx b/client/src/components/meatspace/DeathClockCountdown.jsxnew file mode 100644index 0000000000..8c2c853533--- /dev/null+++ b/client/src/components/meatspace/DeathClockCountdown.jsx@@ -0,0 +1,100 @@+import { useDeathClock } from '../../hooks/useDeathClock';++const TimeUnit = ({ value, label }) => (+ <div className="flex flex-col items-center">+ <span className="text-3xl md:text-5xl font-mono font-bold text-port-error tabular-nums">+ {String(value).padStart(2, '0')}+ </span>+ <span className="text-xs text-gray-500 uppercase mt-1">{label}</span>+ </div>+);++const Separator = () => (+ <span className="text-2xl md:text-4xl font-mono text-gray-600 self-start mt-1">:</span>+);++export default function DeathClockCountdown({ deathDate, lifeExpectancy, percentComplete }) {+ const countdown = useDeathClock(deathDate);++ if (!countdown) {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <p className="text-gray-500">Death clock unavailable. Set birth date in Digital Twin > Goals.</p>+ </div>+ );+ }++ if (countdown.expired) {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <p className="text-port-error text-xl font-bold">Time expired. You're on borrowed time.</p>+ </div>+ );+ }++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-4">Time Remaining</h3>++ {/* Countdown timer */}+ <div className="flex items-start gap-2 md:gap-3 justify-center flex-wrap">+ <TimeUnit value={countdown.years} label="years" />+ <Separator />+ <TimeUnit value={countdown.months} label="months" />+ <Separator />+ <TimeUnit value={countdown.weeks} label="weeks" />+ <Separator />+ <TimeUnit value={countdown.days} label="days" />+ <Separator />+ <TimeUnit value={countdown.hours} label="hours" />+ <Separator />+ <TimeUnit value={countdown.minutes} label="min" />+ <Separator />+ <TimeUnit value={countdown.seconds} label="sec" />+ </div>++ {/* Life expectancy details */}+ {lifeExpectancy && (+ <div className="mt-6 grid grid-cols-2 md:grid-cols-4 gap-4">+ <div>+ <span className="text-xs text-gray-500">SSA Baseline</span>+ <p className="text-lg font-semibold text-gray-300">{lifeExpectancy.baseline}y</p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Genome Adjusted</span>+ <p className="text-lg font-semibold text-gray-300">{lifeExpectancy.genomeAdjusted}y</p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Lifestyle Adj.</span>+ <p className={`text-lg font-semibold ${lifeExpectancy.lifestyleAdjustment >= 0 ? 'text-port-success' : 'text-port-error'}`}>+ {lifeExpectancy.lifestyleAdjustment >= 0 ? '+' : ''}{lifeExpectancy.lifestyleAdjustment}y+ </p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Total LE</span>+ <p className="text-lg font-semibold text-white">{lifeExpectancy.total}y</p>+ </div>+ </div>+ )}++ {/* Progress bar */}+ {percentComplete != null && (+ <div className="mt-4">+ <div className="flex justify-between text-xs text-gray-500 mb-1">+ <span>Life progress</span>+ <span>{percentComplete}%</span>+ </div>+ <div className="h-2 bg-port-border rounded-full overflow-hidden">+ <div+ className="h-full rounded-full transition-all duration-1000"+ style={{+ width: `${Math.min(100, percentComplete)}%`,+ background: percentComplete > 80 ? '#ef4444' : percentComplete > 60 ? '#f59e0b' : '#3b82f6'+ }}+ />+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/meatspace/LEVTracker.jsx b/client/src/components/meatspace/LEVTracker.jsxnew file mode 100644index 0000000000..2416738069--- /dev/null+++ b/client/src/components/meatspace/LEVTracker.jsx@@ -0,0 +1,67 @@+import { Rocket } from 'lucide-react';++export default function LEVTracker({ lev }) {+ if (!lev) return null;++ const { targetYear, ageAtLEV, yearsToLEV, researchProgress, onTrack, adjustedLifeExpectancy } = lev;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <Rocket size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">+ Longevity Escape Velocity — {targetYear}+ </h3>+ </div>++ {/* Status */}+ <div className="flex items-center gap-3 mb-4">+ <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-medium ${+ onTrack+ ? 'bg-port-success/10 text-port-success'+ : 'bg-port-error/10 text-port-error'+ }`}>+ <span className={`w-2 h-2 rounded-full ${onTrack ? 'bg-port-success' : 'bg-port-error'}`} />+ {onTrack ? 'On Track' : 'At Risk'}+ </span>+ <span className="text-sm text-gray-400">+ Age at LEV: <span className="text-white font-medium">{ageAtLEV}</span>+ {' | '}+ Adjusted LE: <span className="text-white font-medium">{adjustedLifeExpectancy}y</span>+ </span>+ </div>++ {/* Research timeline progress */}+ <div className="mb-2">+ <div className="flex justify-between text-xs text-gray-500 mb-1">+ <span>Research timeline (2000–{targetYear})</span>+ <span>{researchProgress}%</span>+ </div>+ <div className="h-3 bg-port-border rounded-full overflow-hidden">+ <div+ className="h-full rounded-full bg-port-accent transition-all duration-500"+ style={{ width: `${researchProgress}%` }}+ />+ </div>+ </div>++ {/* Key stats */}+ <div className="grid grid-cols-3 gap-4 mt-4">+ <div>+ <span className="text-xs text-gray-500">Years to LEV</span>+ <p className="text-xl font-bold text-white">{yearsToLEV}</p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Must survive to age</span>+ <p className="text-xl font-bold text-white">{ageAtLEV}</p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Margin</span>+ <p className={`text-xl font-bold ${onTrack ? 'text-port-success' : 'text-port-error'}`}>+ {onTrack ? '+' : ''}{Math.round((adjustedLifeExpectancy - ageAtLEV) * 10) / 10}y+ </p>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/meatspace/constants.js b/client/src/components/meatspace/constants.jsnew file mode 100644index 0000000000..67a96cf033--- /dev/null+++ b/client/src/components/meatspace/constants.js@@ -0,0 +1,80 @@+import {+ Skull,+ Beer,+ HeartPulse,+ ClipboardList,+ Apple,+ Upload,+ Activity+} from 'lucide-react';++export const TABS = [+ { id: 'overview', label: 'Overview', icon: Activity },+ { id: 'alcohol', label: 'Alcohol', icon: Beer },+ { id: 'blood', label: 'Blood & Body', icon: HeartPulse },+ { id: 'lifestyle', label: 'Lifestyle', icon: ClipboardList },+ { id: 'nutrition', label: 'Nutrition', icon: Apple },+ { id: 'import', label: 'Import', icon: Upload }+];++// Lifestyle adjustment table for death clock+export const LIFESTYLE_ADJUSTMENTS = {+ smoking: { never: 0, former: -2, current: -10 },+ alcohol: { none: 0, moderate: 0.5, heavy: -5 },+ exercise: { high: 2, moderate: 0.5, low: -2 },+ sleep: { optimal: 1, fair: 0, poor: -1.5 },+ diet: { excellent: 2, good: 0.5, fair: 0, poor: -3 },+ stress: { low: 1, moderate: 0, high: -2 },+ bmi: { normal: 0.5, overweight: -0.5, obese: -3 }+};++// NIAAA alcohol thresholds+export const ALCOHOL_THRESHOLDS = {+ male: { dailyMax: 2, weeklyMax: 14 },+ female: { dailyMax: 1, weeklyMax: 7 }+};++// Blood test reference ranges (common panels)+export const REFERENCE_RANGES = {+ // Metabolic Panel+ apoB: { min: 40, max: 100, unit: 'mg/dL', label: 'ApoB' },+ bun: { min: 7, max: 20, unit: 'mg/dL', label: 'BUN' },+ creatinine: { min: 0.7, max: 1.3, unit: 'mg/dL', label: 'Creatinine' },+ egfr: { min: 90, max: 120, unit: 'mL/min', label: 'eGFR' },+ glucose: { min: 70, max: 99, unit: 'mg/dL', label: 'Glucose' },+ // Lipids+ cholesterol: { min: 0, max: 200, unit: 'mg/dL', label: 'Total Cholesterol' },+ hdl: { min: 40, max: 100, unit: 'mg/dL', label: 'HDL' },+ ldl: { min: 0, max: 100, unit: 'mg/dL', label: 'LDL' },+ triglycerides: { min: 0, max: 150, unit: 'mg/dL', label: 'Triglycerides' },+ // CBC+ wbc: { min: 4.5, max: 11.0, unit: 'K/uL', label: 'WBC' },+ rbc: { min: 4.5, max: 5.5, unit: 'M/uL', label: 'RBC' },+ hemoglobin: { min: 13.5, max: 17.5, unit: 'g/dL', label: 'Hemoglobin' },+ hematocrit: { min: 38.3, max: 48.6, unit: '%', label: 'Hematocrit' },+ platelets: { min: 150, max: 400, unit: 'K/uL', label: 'Platelets' },+ // Thyroid+ tsh: { min: 0.4, max: 4.0, unit: 'mIU/L', label: 'TSH' },+ // Other+ homocysteine: { min: 5, max: 15, unit: 'umol/L', label: 'Homocysteine' }+};++// Status colors for blood test values+export const getBloodValueStatus = (value, range) => {+ if (value == null || !range) return 'unknown';+ if (value < range.min) return 'low';+ if (value > range.max) return 'high';+ return 'normal';+};++export const STATUS_COLORS = {+ normal: 'text-port-success',+ low: 'text-port-warning',+ high: 'text-port-error',+ unknown: 'text-gray-500'+};++// LEV 2045 constants+export const LEV_TARGET_YEAR = 2045;+export const LEV_BIRTH_YEAR = 1979;+export const LEV_START_YEAR = 2000; // Research timeline startdiff --git a/client/src/components/meatspace/tabs/AlcoholTab.jsx b/client/src/components/meatspace/tabs/AlcoholTab.jsxnew file mode 100644index 0000000000..d34f8e89ab--- /dev/null+++ b/client/src/components/meatspace/tabs/AlcoholTab.jsx@@ -0,0 +1,16 @@+import { Beer } from 'lucide-react';++export default function AlcoholTab() {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <Beer size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Alcohol Tracking</h3>+ </div>+ <p className="text-gray-500">+ Drink logger with rolling averages, consumption charts, and NIAAA risk thresholds.+ </p>+ <p className="text-sm text-gray-600 mt-2">Coming in Phase 2.</p>+ </div>+ );+}diff --git a/client/src/components/meatspace/tabs/BloodTab.jsx b/client/src/components/meatspace/tabs/BloodTab.jsxnew file mode 100644index 0000000000..38faa72cf2--- /dev/null+++ b/client/src/components/meatspace/tabs/BloodTab.jsx@@ -0,0 +1,17 @@+import { HeartPulse } from 'lucide-react';++export default function BloodTab() {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <HeartPulse size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Blood & Body</h3>+ </div>+ <p className="text-gray-500">+ Blood test panels with reference range highlighting, body composition charts,+ epigenetic age tracking, and eye prescription history.+ </p>+ <p className="text-sm text-gray-600 mt-2">Coming in Phase 3.</p>+ </div>+ );+}diff --git a/client/src/components/meatspace/tabs/ImportTab.jsx b/client/src/components/meatspace/tabs/ImportTab.jsxnew file mode 100644index 0000000000..1f84532c14--- /dev/null+++ b/client/src/components/meatspace/tabs/ImportTab.jsx@@ -0,0 +1,146 @@+import { useState, useRef } from 'react';+import { Upload, FileSpreadsheet, CheckCircle, AlertCircle } from 'lucide-react';+import * as api from '../../../services/api';+import BrailleSpinner from '../../BrailleSpinner';++export default function ImportTab({ onRefresh }) {+ const [importing, setImporting] = useState(false);+ const [result, setResult] = useState(null);+ const [error, setError] = useState(null);+ const [fileName, setFileName] = useState(null);+ const fileInputRef = useRef(null);++ const handleFileSelect = async (e) => {+ const file = e.target.files?.[0];+ if (!file) return;++ setFileName(file.name);+ setError(null);+ setResult(null);+ setImporting(true);++ const reader = new FileReader();+ reader.onload = async (event) => {+ const content = event.target.result;+ const stats = await api.importMeatspaceTSV(content).catch(err => {+ setError(err.message);+ return null;+ });++ if (stats) {+ setResult(stats);+ onRefresh?.();+ }+ setImporting(false);+ };+ reader.onerror = () => {+ setError('Failed to read file');+ setImporting(false);+ };+ reader.readAsText(file);+ };++ return (+ <div className="space-y-6">+ {/* TSV Import */}+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <FileSpreadsheet size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">+ Health Spreadsheet Import (TSV)+ </h3>+ </div>++ <p className="text-sm text-gray-400 mb-4">+ Import your health tracking spreadsheet. Expects a TSV file with 3 header rows,+ 2 summary rows, then daily data. Covers nutrition, alcohol, body composition,+ blood tests, epigenetic results, and eye prescriptions.+ </p>+ <p className="text-xs text-gray-500 mb-4">+ Import is idempotent — re-importing replaces all existing data.+ </p>++ <div className="flex items-center gap-4">+ <input+ ref={fileInputRef}+ type="file"+ accept=".tsv,.txt,.csv"+ onChange={handleFileSelect}+ className="hidden"+ />+ <button+ onClick={() => fileInputRef.current?.click()}+ disabled={importing}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50 transition-colors"+ >+ {importing ? (+ <BrailleSpinner text="Importing" />+ ) : (+ <>+ <Upload size={16} />+ Choose TSV File+ </>+ )}+ </button>+ {fileName && !importing && (+ <span className="text-sm text-gray-400">{fileName}</span>+ )}+ </div>++ {/* Success */}+ {result && (+ <div className="mt-4 p-4 bg-port-success/10 border border-port-success/30 rounded-lg">+ <div className="flex items-center gap-2 mb-2">+ <CheckCircle size={16} className="text-port-success" />+ <span className="text-port-success font-medium">Import successful</span>+ </div>+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">+ <div>+ <span className="text-gray-500">Daily entries</span>+ <p className="text-white font-semibold">{result.dailyEntries}</p>+ </div>+ <div>+ <span className="text-gray-500">Blood tests</span>+ <p className="text-white font-semibold">{result.bloodTests}</p>+ </div>+ <div>+ <span className="text-gray-500">Epigenetic tests</span>+ <p className="text-white font-semibold">{result.epigeneticTests}</p>+ </div>+ <div>+ <span className="text-gray-500">Eye exams</span>+ <p className="text-white font-semibold">{result.eyeExams}</p>+ </div>+ </div>+ {result.dateRange && (+ <p className="text-xs text-gray-400 mt-2">+ Date range: {result.dateRange.from} to {result.dateRange.to}+ </p>+ )}+ </div>+ )}++ {/* Error */}+ {error && (+ <div className="mt-4 p-4 bg-port-error/10 border border-port-error/30 rounded-lg">+ <div className="flex items-center gap-2">+ <AlertCircle size={16} className="text-port-error" />+ <span className="text-port-error">{error}</span>+ </div>+ </div>+ )}+ </div>++ {/* Apple Health Placeholder */}+ <div className="bg-port-card border border-port-border rounded-xl p-6 opacity-60">+ <div className="flex items-center gap-2 mb-2">+ <Upload size={18} className="text-gray-500" />+ <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wider">+ Apple Health Import+ </h3>+ </div>+ <p className="text-sm text-gray-500">Coming soon — import from Apple Health XML export.</p>+ </div>+ </div>+ );+}diff --git a/client/src/components/meatspace/tabs/LifestyleTab.jsx b/client/src/components/meatspace/tabs/LifestyleTab.jsxnew file mode 100644index 0000000000..3223082a57--- /dev/null+++ b/client/src/components/meatspace/tabs/LifestyleTab.jsx@@ -0,0 +1,17 @@+import { ClipboardList } from 'lucide-react';++export default function LifestyleTab() {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <ClipboardList size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Lifestyle Questionnaire</h3>+ </div>+ <p className="text-gray-500">+ Smoking, drinking, exercise, sleep, diet quality, stress level, and BMI inputs.+ Updates feed into death clock calculation.+ </p>+ <p className="text-sm text-gray-600 mt-2">Coming in Phase 4.</p>+ </div>+ );+}diff --git a/client/src/components/meatspace/tabs/NutritionTab.jsx b/client/src/components/meatspace/tabs/NutritionTab.jsxnew file mode 100644index 0000000000..d6392bf165--- /dev/null+++ b/client/src/components/meatspace/tabs/NutritionTab.jsx@@ -0,0 +1,16 @@+import { Apple } from 'lucide-react';++export default function NutritionTab() {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <div className="flex items-center gap-2 mb-4">+ <Apple size={18} className="text-port-accent" />+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">Nutrition</h3>+ </div>+ <p className="text-gray-500">+ Macro tracking, mercury exposure from seafood, daily limits vs actuals.+ </p>+ <p className="text-sm text-gray-600 mt-2">Coming in Phase 4.</p>+ </div>+ );+}diff --git a/client/src/components/meatspace/tabs/OverviewTab.jsx b/client/src/components/meatspace/tabs/OverviewTab.jsxnew file mode 100644index 0000000000..729eb8953b--- /dev/null+++ b/client/src/components/meatspace/tabs/OverviewTab.jsx@@ -0,0 +1,104 @@+import { useState, useEffect, useCallback } from 'react';+import * as api from '../../../services/api';+import DeathClockCountdown from '../DeathClockCountdown';+import LEVTracker from '../LEVTracker';+import BrailleSpinner from '../../BrailleSpinner';++export default function OverviewTab() {+ const [data, setData] = useState(null);+ const [loading, setLoading] = useState(true);++ const fetchData = useCallback(async () => {+ const result = await api.getMeatspaceOverview().catch(() => null);+ setData(result);+ setLoading(false);+ }, []);++ useEffect(() => {+ fetchData();+ const interval = setInterval(fetchData, 60000);+ return () => clearInterval(interval);+ }, [fetchData]);++ if (loading) {+ return (+ <div className="flex items-center justify-center h-64">+ <BrailleSpinner text="Loading" />+ </div>+ );+ }++ if (!data) {+ return <p className="text-gray-500">Failed to load overview data.</p>;+ }++ const { deathClock, lev, summary } = data;++ return (+ <div className="space-y-6">+ {/* Death Clock */}+ {deathClock?.error ? (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <p className="text-port-warning">{deathClock.error}</p>+ </div>+ ) : (+ <DeathClockCountdown+ deathDate={deathClock?.deathDate}+ lifeExpectancy={deathClock?.lifeExpectancy}+ percentComplete={deathClock?.percentComplete}+ />+ )}++ {/* LEV Tracker */}+ <LEVTracker lev={lev} />++ {/* Health Summary */}+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-4">Data Summary</h3>+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">+ <div>+ <span className="text-xs text-gray-500">Daily Entries</span>+ <p className="text-2xl font-bold text-white">{summary?.totalEntries || 0}</p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Last Entry</span>+ <p className="text-lg font-semibold text-gray-300">{summary?.lastEntryDate || 'None'}</p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Genome Data</span>+ <p className={`text-lg font-semibold ${summary?.hasGenomeData ? 'text-port-success' : 'text-gray-500'}`}>+ {summary?.hasGenomeData ? 'Active' : 'Missing'}+ </p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Lifestyle Profile</span>+ <p className={`text-lg font-semibold ${summary?.hasLifestyleData ? 'text-port-success' : 'text-gray-500'}`}>+ {summary?.hasLifestyleData ? 'Active' : 'Not Set'}+ </p>+ </div>+ </div>+ </div>++ {/* Quick Info */}+ {deathClock && !deathClock.error && (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-4">Vitals</h3>+ <div className="grid grid-cols-2 md:grid-cols-3 gap-4">+ <div>+ <span className="text-xs text-gray-500">Current Age</span>+ <p className="text-xl font-bold text-white">{deathClock.ageYears}y</p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Years Remaining</span>+ <p className="text-xl font-bold text-port-warning">{deathClock.yearsRemaining}y</p>+ </div>+ <div>+ <span className="text-xs text-gray-500">Healthy Years</span>+ <p className="text-xl font-bold text-port-success">{deathClock.healthyYearsRemaining}y</p>+ </div>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/hooks/useDeathClock.js b/client/src/hooks/useDeathClock.jsnew file mode 100644index 0000000000..e2375d79e2--- /dev/null+++ b/client/src/hooks/useDeathClock.js@@ -0,0 +1,67 @@+import { useState, useEffect, useRef } from 'react';++/**+ * 1-second countdown hook for death clock display.+ * Takes a deathDate ISO string, returns live countdown breakdown.+ */+export function useDeathClock(deathDateISO) {+ const [countdown, setCountdown] = useState(null);+ const intervalRef = useRef(null);++ useEffect(() => {+ if (!deathDateISO) {+ setCountdown(null);+ return;+ }++ const deathDate = new Date(deathDateISO);++ const update = () => {+ const now = new Date();+ const diff = deathDate.getTime() - now.getTime();++ if (diff <= 0) {+ setCountdown({ expired: true, years: 0, months: 0, weeks: 0, days: 0, hours: 0, minutes: 0, seconds: 0 });+ return;+ }++ // Calculate breakdown+ const totalSeconds = Math.floor(diff / 1000);+ const totalMinutes = Math.floor(totalSeconds / 60);+ const totalHours = Math.floor(totalMinutes / 60);+ const totalDays = Math.floor(totalHours / 24);++ const years = Math.floor(totalDays / 365.25);+ const remainingDaysAfterYears = totalDays - Math.floor(years * 365.25);+ const months = Math.floor(remainingDaysAfterYears / 30.44);+ const remainingDaysAfterMonths = remainingDaysAfterYears - Math.floor(months * 30.44);+ const weeks = Math.floor(remainingDaysAfterMonths / 7);+ const days = remainingDaysAfterMonths - weeks * 7;+ const hours = totalHours % 24;+ const minutes = totalMinutes % 60;+ const seconds = totalSeconds % 60;++ setCountdown({+ expired: false,+ years,+ months,+ weeks,+ days,+ hours,+ minutes,+ seconds,+ totalDays,+ totalHours: totalHours % 24+ });+ };++ update();+ intervalRef.current = setInterval(update, 1000);++ return () => {+ if (intervalRef.current) clearInterval(intervalRef.current);+ };+ }, [deathDateISO]);++ return countdown;+}diff --git a/client/src/pages/MeatSpace.jsx b/client/src/pages/MeatSpace.jsxnew file mode 100644index 0000000000..1b8e4217ac--- /dev/null+++ b/client/src/pages/MeatSpace.jsx@@ -0,0 +1,76 @@+import { useParams, useNavigate } from 'react-router-dom';+import { Skull } from 'lucide-react';++import { TABS } from '../components/meatspace/constants';++import OverviewTab from '../components/meatspace/tabs/OverviewTab';+import AlcoholTab from '../components/meatspace/tabs/AlcoholTab';+import BloodTab from '../components/meatspace/tabs/BloodTab';+import LifestyleTab from '../components/meatspace/tabs/LifestyleTab';+import NutritionTab from '../components/meatspace/tabs/NutritionTab';+import ImportTab from '../components/meatspace/tabs/ImportTab';++export default function MeatSpace() {+ const { tab } = useParams();+ const navigate = useNavigate();+ const activeTab = tab || 'overview';++ const handleTabChange = (tabId) => {+ navigate(`/meatspace/${tabId}`);+ };++ const renderTabContent = () => {+ switch (activeTab) {+ case 'overview':+ return <OverviewTab />;+ case 'alcohol':+ return <AlcoholTab />;+ case 'blood':+ return <BloodTab />;+ case 'lifestyle':+ return <LifestyleTab />;+ case 'nutrition':+ return <NutritionTab />;+ case 'import':+ return <ImportTab />;+ default:+ return <OverviewTab />;+ }+ };++ return (+ <div className="flex flex-col h-full">+ {/* Header */}+ <div className="flex-shrink-0 px-6 pt-6 pb-4 border-b border-port-border">+ <div className="flex items-center gap-3 mb-4">+ <Skull size={24} className="text-port-error" />+ <h1 className="text-2xl font-bold text-white">MeatSpace</h1>+ <span className="text-sm text-gray-500">Physical Health Dashboard</span>+ </div>++ {/* Tabs */}+ <div className="flex gap-1 overflow-x-auto">+ {TABS.map(({ id, label, icon: Icon }) => (+ <button+ key={id}+ onClick={() => handleTabChange(id)}+ className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors ${+ activeTab === id+ ? 'bg-port-accent/10 text-port-accent'+ : 'text-gray-400 hover:text-white hover:bg-port-border/50'+ }`}+ >+ <Icon size={16} />+ {label}+ </button>+ ))}+ </div>+ </div>++ {/* Tab content */}+ <div className="flex-1 overflow-auto p-6">+ {renderTabContent()}+ </div>+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 7d3b5b0846..6fcf48365c 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1259,6 +1259,24 @@ export const addGoalMilestone = (goalId, data) => request(`/digital-twin/identitexport const completeGoalMilestone = (goalId, milestoneId) =>request(`/digital-twin/identity/goals/${goalId}/milestones/${milestoneId}/complete`, { method: 'PUT' });+// MeatSpace - Health Tracker+export const getMeatspaceOverview = () => request('/meatspace');+export const getMeatspaceConfig = () => request('/meatspace/config');+export const updateMeatspaceConfig = (data) => request('/meatspace/config', {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const updateMeatspaceLifestyle = (data) => request('/meatspace/lifestyle', {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const getDeathClock = () => request('/meatspace/death-clock');+export const getLEV = () => request('/meatspace/lev');+export const importMeatspaceTSV = (content) => request('/meatspace/import/tsv', {+ method: 'POST',+ body: JSON.stringify({ content })+});+// JIRAexport const getJiraInstances = () => request('/jira/instances');export const getJiraProjects = (instanceId) => request(`/jira/instances/${instanceId}/projects`);diff --git a/package-lock.json b/package-lock.jsonindex 28cd9d9e09..fb266a75b1 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "portos",- "version": "1.8.6",+ "version": "1.9.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos",- "version": "1.8.6",+ "version": "1.9.0","license": "MIT","dependencies": {"express": "^4.21.2",diff --git a/package.json b/package.jsonindex a1c64360e7..8005afb266 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portos",- "version": "1.8.6",+ "version": "1.9.0","private": true,"description": "Local dev machine App OS portal","author": "Adam Eivy (@antic|@atomantic)",diff --git a/server/index.js b/server/index.jsindex aa87155619..3e1f475a87 100644--- a/server/index.js+++ b/server/index.js@@ -42,6 +42,7 @@ import jiraRoutes from './routes/jira.js';import autobiographyRoutes from './routes/autobiography.js';import identityRoutes from './routes/identity.js';import instancesRoutes from './routes/instances.js';+import meatspaceRoutes from './routes/meatspace.js';import settingsRoutes from './routes/settings.js';import { ensureSelf, startPolling } from './services/instances.js';import { initSocket } from './services/socket.js';@@ -213,6 +214,7 @@ app.use('/api/lmstudio', lmstudioRoutes);app.use('/api/browser', browserRoutes);app.use('/api/jira', jiraRoutes);app.use('/api/instances', instancesRoutes);+app.use('/api/meatspace', meatspaceRoutes);app.use('/api/settings', settingsRoutes);// Initialize script runnerdiff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex e659695c56..a900db186a 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -27,7 +27,8 @@ export const PATHS = {scripts: join(__lib_dirname, '../../data/cos/scripts'),reports: join(__lib_dirname, '../../data/cos/reports'),// AI Agent Personalities data- agentPersonalities: join(__lib_dirname, '../../data/agents')+ agentPersonalities: join(__lib_dirname, '../../data/agents'),+ meatspace: join(__lib_dirname, '../../data/meatspace')};/**diff --git a/server/lib/meatspaceValidation.js b/server/lib/meatspaceValidation.jsnew file mode 100644index 0000000000..ab9097e370--- /dev/null+++ b/server/lib/meatspaceValidation.js@@ -0,0 +1,103 @@+import { z } from 'zod';++// =============================================================================+// MEATSPACE CONFIG & LIFESTYLE+// =============================================================================++export const smokingStatusSchema = z.enum(['never', 'former', 'current']);+export const dietQualitySchema = z.enum(['excellent', 'good', 'fair', 'poor']);+export const stressLevelSchema = z.enum(['low', 'moderate', 'high']);++export const lifestyleSchema = z.object({+ smokingStatus: smokingStatusSchema.optional().default('never'),+ alcoholDrinksPerDay: z.number().min(0).max(50).optional(),+ exerciseMinutesPerWeek: z.number().min(0).max(2000).optional().default(150),+ sleepHoursPerNight: z.number().min(0).max(24).optional().default(7.5),+ dietQuality: dietQualitySchema.optional().default('good'),+ stressLevel: stressLevelSchema.optional().default('moderate'),+ bmi: z.number().min(10).max(80).optional(),+ chronicConditions: z.array(z.string().max(100)).optional().default([])+});++export const configSchema = z.object({+ sex: z.enum(['male', 'female']).optional(),+ sexSource: z.enum(['genome', 'questionnaire']).optional(),+ lifestyle: lifestyleSchema.optional()+});++export const configUpdateSchema = configSchema.partial();+export const lifestyleUpdateSchema = lifestyleSchema.partial();++// =============================================================================+// ALCOHOL+// =============================================================================++export const drinkLogSchema = z.object({+ name: z.string().max(200).optional().default(''),+ oz: z.number().min(0.1).max(1000),+ abv: z.number().min(0).max(100),+ count: z.number().int().min(1).max(100).optional().default(1),+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()+});++// =============================================================================+// BLOOD TESTS+// =============================================================================++export const bloodTestSchema = z.object({+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),+ metabolicPanel: z.record(z.number().nullable()).optional(),+ cbc: z.record(z.number().nullable()).optional(),+ lipids: z.record(z.number().nullable()).optional(),+ thyroid: z.record(z.number().nullable()).optional(),+ hormones: z.record(z.number().nullable()).optional(),+ homocysteine: z.number().nullable().optional()+});++// =============================================================================+// BODY COMPOSITION+// =============================================================================++export const bodyEntrySchema = z.object({+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),+ weightLbs: z.number().min(50).max(1000).optional(),+ weightKg: z.number().min(20).max(500).optional(),+ musclePct: z.number().min(0).max(100).nullable().optional(),+ fatPct: z.number().min(0).max(100).nullable().optional(),+ boneMass: z.number().nullable().optional(),+ temperature: z.number().nullable().optional()+});++// =============================================================================+// EPIGENETIC TESTS+// =============================================================================++export const epigeneticTestSchema = z.object({+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),+ chronologicalAge: z.number().min(0).max(150).optional(),+ biologicalAge: z.number().min(0).max(150).optional(),+ paceOfAging: z.number().min(0).max(5).optional(),+ organScores: z.record(z.number().nullable()).optional()+});++// =============================================================================+// EYES+// =============================================================================++export const eyeExamSchema = z.object({+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),+ rightSphere: z.number().nullable().optional(),+ rightCylinder: z.number().nullable().optional(),+ rightAxis: z.number().nullable().optional(),+ leftSphere: z.number().nullable().optional(),+ leftCylinder: z.number().nullable().optional(),+ leftAxis: z.number().nullable().optional()+});++// =============================================================================+// TSV IMPORT+// =============================================================================++export const tsvImportSchema = z.object({+ content: z.string().min(1).max(10 * 1024 * 1024)+});diff --git a/server/routes/meatspace.js b/server/routes/meatspace.jsnew file mode 100644index 0000000000..e8cb4789c5--- /dev/null+++ b/server/routes/meatspace.js@@ -0,0 +1,99 @@+import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import {+ configUpdateSchema,+ lifestyleUpdateSchema,+ tsvImportSchema+} from '../lib/meatspaceValidation.js';+import * as meatspaceService from '../services/meatspace.js';+import { importTSV } from '../services/meatspaceImport.js';++const router = Router();++// =============================================================================+// OVERVIEW+// =============================================================================++/**+ * GET /api/meatspace+ * Overview: death clock, LEV, health summary+ */+router.get('/', asyncHandler(async (req, res) => {+ const overview = await meatspaceService.getOverview();+ res.json(overview);+}));++// =============================================================================+// CONFIG+// =============================================================================++/**+ * GET /api/meatspace/config+ * Profile + lifestyle config+ */+router.get('/config', asyncHandler(async (req, res) => {+ const config = await meatspaceService.getConfig();+ res.json(config);+}));++/**+ * PUT /api/meatspace/config+ * Update profile config+ */+router.put('/config', asyncHandler(async (req, res) => {+ const data = validateRequest(configUpdateSchema, req.body);+ const config = await meatspaceService.updateConfig(data);+ res.json(config);+}));++/**+ * PUT /api/meatspace/lifestyle+ * Update lifestyle questionnaire+ */+router.put('/lifestyle', asyncHandler(async (req, res) => {+ const data = validateRequest(lifestyleUpdateSchema, req.body);+ const config = await meatspaceService.updateLifestyle(data);+ res.json(config);+}));++// =============================================================================+// DEATH CLOCK & LEV+// =============================================================================++/**+ * GET /api/meatspace/death-clock+ * Full death clock computation+ */+router.get('/death-clock', asyncHandler(async (req, res) => {+ const deathClock = await meatspaceService.getDeathClock();+ res.json(deathClock);+}));++/**+ * GET /api/meatspace/lev+ * LEV 2045 tracker data+ */+router.get('/lev', asyncHandler(async (req, res) => {+ const lev = await meatspaceService.getLEV();+ res.json(lev);+}));++// =============================================================================+// IMPORT+// =============================================================================++/**+ * POST /api/meatspace/import/tsv+ * Import TSV spreadsheet (5MB limit handled by express.json middleware)+ */+router.post('/import/tsv', asyncHandler(async (req, res) => {+ const { content } = validateRequest(tsvImportSchema, req.body);+ const stats = await importTSV(content);+ if (stats.error) {+ throw new ServerError(stats.error, { status: 400, code: 'IMPORT_FAILED' });+ }+ res.json(stats);+}));++export default router;diff --git a/server/services/meatspace.js b/server/services/meatspace.jsnew file mode 100644index 0000000000..ccb0b2f40e--- /dev/null+++ b/server/services/meatspace.js@@ -0,0 +1,275 @@+/**+ * MeatSpace Core Service+ *+ * Config CRUD, sex detection from genome, death clock computation,+ * and LEV 2045 tracker. Reads genome/longevity data from Digital Twin.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { getSnpIndex } from './genome.js';++const MEATSPACE_DIR = PATHS.meatspace;+const CONFIG_FILE = join(MEATSPACE_DIR, 'config.json');+const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');++// Digital Twin paths (read-only)+const LONGEVITY_FILE = join(PATHS.digitalTwin, 'longevity.json');+const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');++const SSA_BASELINE = 78.5;++const DEFAULT_CONFIG = {+ sex: null,+ sexSource: null,+ lifestyle: {+ smokingStatus: 'never',+ exerciseMinutesPerWeek: 150,+ sleepHoursPerNight: 7.5,+ dietQuality: 'good',+ stressLevel: 'moderate',+ bmi: null,+ chronicConditions: []+ },+ updatedAt: null+};++const LEV_TARGET_YEAR = 2045;+const LEV_BIRTH_YEAR = 1979;+const LEV_START_YEAR = 2000;++// === File I/O ===++async function ensureMeatspaceDir() {+ await ensureDir(MEATSPACE_DIR);+}++async function loadConfig() {+ return readJSONFile(CONFIG_FILE, structuredClone(DEFAULT_CONFIG));+}++async function saveConfig(config) {+ await ensureMeatspaceDir();+ await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));+}++// === Sex Detection ===++export async function detectSexFromGenome() {+ const index = await getSnpIndex();+ if (!index) return null;++ let yCount = 0;+ for (const [, snp] of index) {+ if (snp.chromosome === 'Y') yCount++;+ }+ return yCount > 1000 ? 'male' : 'female';+}++// === Lifestyle Adjustments (Pure) ===++export function computeLifestyleAdjustment(lifestyle) {+ if (!lifestyle) return 0;++ let adj = 0;++ // Smoking+ const smoking = lifestyle.smokingStatus || 'never';+ if (smoking === 'never') adj += 0;+ else if (smoking === 'former') adj -= 2;+ else if (smoking === 'current') adj -= 10;++ // Alcohol (from daily average or questionnaire)+ const drinks = lifestyle.alcoholDrinksPerDay;+ if (drinks != null) {+ if (drinks <= 2) adj += 0.5;+ else if (drinks > 3) adj -= 5;+ }++ // Exercise+ const exercise = lifestyle.exerciseMinutesPerWeek ?? 150;+ if (exercise > 150) adj += 2;+ else if (exercise >= 75) adj += 0.5;+ else adj -= 2;++ // Sleep+ const sleep = lifestyle.sleepHoursPerNight ?? 7.5;+ if (sleep >= 7 && sleep <= 9) adj += 1;+ else if (sleep >= 6 && sleep < 7) adj += 0;+ else adj -= 1.5;++ // Diet+ const diet = lifestyle.dietQuality || 'good';+ if (diet === 'excellent') adj += 2;+ else if (diet === 'good') adj += 0.5;+ else if (diet === 'fair') adj += 0;+ else adj -= 3;++ // Stress+ const stress = lifestyle.stressLevel || 'moderate';+ if (stress === 'low') adj += 1;+ else if (stress === 'moderate') adj += 0;+ else adj -= 2;++ // BMI+ const bmi = lifestyle.bmi;+ if (bmi != null) {+ if (bmi >= 18.5 && bmi < 25) adj += 0.5;+ else if (bmi >= 25 && bmi < 30) adj -= 0.5;+ else if (bmi >= 30) adj -= 3;+ }++ return Math.round(adj * 100) / 100;+}++// === Death Clock ===++export function computeDeathClock(birthDate, genomeAdjustedLE, lifestyleAdj) {+ const baseline = genomeAdjustedLE ?? SSA_BASELINE;+ const totalLE = baseline + lifestyleAdj;++ const birth = new Date(birthDate);+ const deathDate = new Date(birth);+ deathDate.setFullYear(deathDate.getFullYear() + Math.floor(totalLE));+ deathDate.setMonth(deathDate.getMonth() + Math.round((totalLE % 1) * 12));++ const now = new Date();+ const msRemaining = deathDate.getTime() - now.getTime();+ const ageYears = (now - birth) / (365.25 * 24 * 60 * 60 * 1000);+ const yearsRemaining = Math.max(0, totalLE - ageYears);+ const healthyYearsRemaining = Math.round(yearsRemaining * 0.85 * 10) / 10;+ const percentComplete = Math.min(100, Math.round((ageYears / totalLE) * 1000) / 10);++ return {+ birthDate,+ deathDate: deathDate.toISOString(),+ msRemaining: Math.max(0, msRemaining),+ lifeExpectancy: {+ baseline: SSA_BASELINE,+ genomeAdjusted: genomeAdjustedLE ?? SSA_BASELINE,+ lifestyleAdjustment: lifestyleAdj,+ total: Math.round(totalLE * 10) / 10+ },+ ageYears: Math.round(ageYears * 100) / 100,+ yearsRemaining: Math.round(yearsRemaining * 100) / 100,+ healthyYearsRemaining,+ percentComplete+ };+}++// === LEV Tracker ===++export function computeLEV(birthDate, adjustedLE) {+ const now = new Date();+ const currentYear = now.getFullYear() + now.getMonth() / 12;+ const ageAtLEV = LEV_TARGET_YEAR - LEV_BIRTH_YEAR;+ const yearsToLEV = LEV_TARGET_YEAR - currentYear;+ const researchProgress = Math.round(((currentYear - LEV_START_YEAR) / (LEV_TARGET_YEAR - LEV_START_YEAR)) * 1000) / 10;+ const onTrack = adjustedLE > ageAtLEV;++ return {+ targetYear: LEV_TARGET_YEAR,+ ageAtLEV,+ yearsToLEV: Math.round(yearsToLEV * 10) / 10,+ researchProgress: Math.min(100, researchProgress),+ onTrack,+ adjustedLifeExpectancy: adjustedLE+ };+}++// === Exported Service Functions ===++export async function getConfig() {+ const config = await loadConfig();++ // Auto-detect sex from genome if not set+ if (!config.sex) {+ const detectedSex = await detectSexFromGenome();+ if (detectedSex) {+ config.sex = detectedSex;+ config.sexSource = 'genome';+ config.updatedAt = new Date().toISOString();+ await saveConfig(config);+ console.log(`🧬 Sex auto-detected from genome: ${detectedSex}`);+ }+ }++ return config;+}++export async function updateConfig(updates) {+ const config = await loadConfig();+ if (updates.sex !== undefined) config.sex = updates.sex;+ if (updates.sexSource !== undefined) config.sexSource = updates.sexSource;+ if (updates.lifestyle) {+ config.lifestyle = { ...config.lifestyle, ...updates.lifestyle };+ }+ config.updatedAt = new Date().toISOString();+ await saveConfig(config);+ return config;+}++export async function updateLifestyle(updates) {+ const config = await loadConfig();+ config.lifestyle = { ...config.lifestyle, ...updates };+ config.updatedAt = new Date().toISOString();+ await saveConfig(config);+ return config;+}++export async function getDeathClock() {+ const [config, longevity, goals] = await Promise.all([+ loadConfig(),+ readJSONFile(LONGEVITY_FILE, null),+ readJSONFile(GOALS_FILE, null)+ ]);++ const birthDate = goals?.birthDate;+ if (!birthDate) {+ return { error: 'Birth date not set. Set it in Digital Twin > Goals.' };+ }++ const genomeAdjusted = longevity?.lifeExpectancy?.adjusted ?? null;+ const lifestyleAdj = computeLifestyleAdjustment(config.lifestyle);++ return computeDeathClock(birthDate, genomeAdjusted, lifestyleAdj);+}++export async function getLEV() {+ const [longevity, goals, config] = await Promise.all([+ readJSONFile(LONGEVITY_FILE, null),+ readJSONFile(GOALS_FILE, null),+ loadConfig()+ ]);++ const genomeAdjusted = longevity?.lifeExpectancy?.adjusted ?? SSA_BASELINE;+ const lifestyleAdj = computeLifestyleAdjustment(config.lifestyle);+ const totalLE = genomeAdjusted + lifestyleAdj;++ return computeLEV(goals?.birthDate, totalLE);+}++export async function getOverview() {+ const [config, deathClock, lev, dailyLog] = await Promise.all([+ getConfig(),+ getDeathClock(),+ getLEV(),+ readJSONFile(DAILY_LOG_FILE, { entries: [] })+ ]);++ const entryCount = dailyLog.entries?.length || 0;+ const lastEntry = dailyLog.entries?.[entryCount - 1] || null;++ return {+ config,+ deathClock,+ lev,+ summary: {+ totalEntries: entryCount,+ lastEntryDate: lastEntry?.date || null,+ hasGenomeData: deathClock.lifeExpectancy?.genomeAdjusted !== SSA_BASELINE,+ hasLifestyleData: !!config.lifestyle?.smokingStatus+ }+ };+}diff --git a/server/services/meatspace.test.js b/server/services/meatspace.test.jsnew file mode 100644index 0000000000..24aca93083--- /dev/null+++ b/server/services/meatspace.test.js@@ -0,0 +1,244 @@+import { describe, it, expect } from 'vitest';++// Inline copies of pure functions to avoid complex mocking+// (follows existing test pattern in subAgentSpawner.test.js)++function computeLifestyleAdjustment(lifestyle) {+ if (!lifestyle) return 0;+ let adj = 0;++ const smoking = lifestyle.smokingStatus || 'never';+ if (smoking === 'never') adj += 0;+ else if (smoking === 'former') adj -= 2;+ else if (smoking === 'current') adj -= 10;++ const drinks = lifestyle.alcoholDrinksPerDay;+ if (drinks != null) {+ if (drinks <= 2) adj += 0.5;+ else if (drinks > 3) adj -= 5;+ }++ const exercise = lifestyle.exerciseMinutesPerWeek ?? 150;+ if (exercise > 150) adj += 2;+ else if (exercise >= 75) adj += 0.5;+ else adj -= 2;++ const sleep = lifestyle.sleepHoursPerNight ?? 7.5;+ if (sleep >= 7 && sleep <= 9) adj += 1;+ else if (sleep >= 6 && sleep < 7) adj += 0;+ else adj -= 1.5;++ const diet = lifestyle.dietQuality || 'good';+ if (diet === 'excellent') adj += 2;+ else if (diet === 'good') adj += 0.5;+ else if (diet === 'fair') adj += 0;+ else adj -= 3;++ const stress = lifestyle.stressLevel || 'moderate';+ if (stress === 'low') adj += 1;+ else if (stress === 'moderate') adj += 0;+ else adj -= 2;++ const bmi = lifestyle.bmi;+ if (bmi != null) {+ if (bmi >= 18.5 && bmi < 25) adj += 0.5;+ else if (bmi >= 25 && bmi < 30) adj -= 0.5;+ else if (bmi >= 30) adj -= 3;+ }++ return Math.round(adj * 100) / 100;+}++function computeDeathClock(birthDate, genomeAdjustedLE, lifestyleAdj) {+ const SSA_BASELINE = 78.5;+ const baseline = genomeAdjustedLE ?? SSA_BASELINE;+ const totalLE = baseline + lifestyleAdj;++ const birth = new Date(birthDate);+ const deathDate = new Date(birth);+ deathDate.setFullYear(deathDate.getFullYear() + Math.floor(totalLE));+ deathDate.setMonth(deathDate.getMonth() + Math.round((totalLE % 1) * 12));++ const now = new Date();+ const msRemaining = deathDate.getTime() - now.getTime();+ const ageYears = (now - birth) / (365.25 * 24 * 60 * 60 * 1000);+ const yearsRemaining = Math.max(0, totalLE - ageYears);+ const healthyYearsRemaining = Math.round(yearsRemaining * 0.85 * 10) / 10;+ const percentComplete = Math.min(100, Math.round((ageYears / totalLE) * 1000) / 10);++ return {+ birthDate,+ deathDate: deathDate.toISOString(),+ msRemaining: Math.max(0, msRemaining),+ lifeExpectancy: {+ baseline: SSA_BASELINE,+ genomeAdjusted: genomeAdjustedLE ?? SSA_BASELINE,+ lifestyleAdjustment: lifestyleAdj,+ total: Math.round(totalLE * 10) / 10+ },+ ageYears: Math.round(ageYears * 100) / 100,+ yearsRemaining: Math.round(yearsRemaining * 100) / 100,+ healthyYearsRemaining,+ percentComplete+ };+}++function computeLEV(birthDate, adjustedLE) {+ const LEV_TARGET_YEAR = 2045;+ const LEV_BIRTH_YEAR = 1979;+ const LEV_START_YEAR = 2000;++ const now = new Date();+ const currentYear = now.getFullYear() + now.getMonth() / 12;+ const ageAtLEV = LEV_TARGET_YEAR - LEV_BIRTH_YEAR;+ const yearsToLEV = LEV_TARGET_YEAR - currentYear;+ const researchProgress = Math.round(((currentYear - LEV_START_YEAR) / (LEV_TARGET_YEAR - LEV_START_YEAR)) * 1000) / 10;+ const onTrack = adjustedLE > ageAtLEV;++ return {+ targetYear: LEV_TARGET_YEAR,+ ageAtLEV,+ yearsToLEV: Math.round(yearsToLEV * 10) / 10,+ researchProgress: Math.min(100, researchProgress),+ onTrack,+ adjustedLifeExpectancy: adjustedLE+ };+}++// =============================================================================+// LIFESTYLE ADJUSTMENT TESTS+// =============================================================================++describe('computeLifestyleAdjustment', () => {+ it('returns 0 for null/undefined lifestyle', () => {+ expect(computeLifestyleAdjustment(null)).toBe(0);+ expect(computeLifestyleAdjustment(undefined)).toBe(0);+ });++ it('computes optimal lifestyle bonus', () => {+ const lifestyle = {+ smokingStatus: 'never',+ alcoholDrinksPerDay: 1,+ exerciseMinutesPerWeek: 200,+ sleepHoursPerNight: 8,+ dietQuality: 'excellent',+ stressLevel: 'low',+ bmi: 22+ };+ // never: +0, alcohol<=2: +0.5, >150min: +2, 7-9h: +1, excellent: +2, low: +1, normal bmi: +0.5+ expect(computeLifestyleAdjustment(lifestyle)).toBe(7);+ });++ it('computes worst-case lifestyle penalty', () => {+ const lifestyle = {+ smokingStatus: 'current',+ alcoholDrinksPerDay: 5,+ exerciseMinutesPerWeek: 30,+ sleepHoursPerNight: 5,+ dietQuality: 'poor',+ stressLevel: 'high',+ bmi: 35+ };+ // current: -10, heavy: -5, <75min: -2, <6h: -1.5, poor: -3, high: -2, obese: -3+ expect(computeLifestyleAdjustment(lifestyle)).toBe(-26.5);+ });++ it('handles default lifestyle (empty object)', () => {+ // Default: never(0), no alcohol(skip), 150(+0.5), 7.5(+1), good(+0.5), moderate(0), no bmi(skip)+ const adj = computeLifestyleAdjustment({});+ expect(adj).toBe(2);+ });++ it('handles former smoker', () => {+ const lifestyle = {+ smokingStatus: 'former',+ exerciseMinutesPerWeek: 100,+ sleepHoursPerNight: 7.5,+ dietQuality: 'good',+ stressLevel: 'moderate'+ };+ // former: -2, 75-150: +0.5, 7-9h: +1, good: +0.5, moderate: 0+ expect(computeLifestyleAdjustment(lifestyle)).toBe(0);+ });++ it('handles overweight BMI', () => {+ const lifestyle = { bmi: 27, exerciseMinutesPerWeek: 150, sleepHoursPerNight: 7.5, dietQuality: 'good' };+ // never: 0, exercise 150(+0.5), sleep(+1), good(+0.5), moderate(0), overweight(-0.5)+ expect(computeLifestyleAdjustment(lifestyle)).toBe(1.5);+ });+});++// =============================================================================+// DEATH CLOCK TESTS+// =============================================================================++describe('computeDeathClock', () => {+ it('computes death date from birth date and life expectancy', () => {+ const result = computeDeathClock('1979-07-31', 76.9, 2);+ expect(result.birthDate).toBe('1979-07-31');+ expect(result.lifeExpectancy.baseline).toBe(78.5);+ expect(result.lifeExpectancy.genomeAdjusted).toBe(76.9);+ expect(result.lifeExpectancy.lifestyleAdjustment).toBe(2);+ expect(result.lifeExpectancy.total).toBe(78.9);+ expect(result.msRemaining).toBeGreaterThan(0);+ expect(result.ageYears).toBeGreaterThan(46);+ expect(result.yearsRemaining).toBeGreaterThan(0);+ expect(result.percentComplete).toBeGreaterThan(50);+ });++ it('uses SSA baseline when genome data is null', () => {+ const result = computeDeathClock('1979-07-31', null, 0);+ expect(result.lifeExpectancy.genomeAdjusted).toBe(78.5);+ expect(result.lifeExpectancy.total).toBe(78.5);+ });++ it('applies negative lifestyle adjustment', () => {+ const result = computeDeathClock('1979-07-31', 76.9, -10);+ expect(result.lifeExpectancy.total).toBe(66.9);+ expect(result.yearsRemaining).toBeLessThan(25);+ });++ it('clamps msRemaining to 0 for past death dates', () => {+ const result = computeDeathClock('1900-01-01', 50, 0);+ expect(result.msRemaining).toBe(0);+ expect(result.yearsRemaining).toBe(0);+ expect(result.percentComplete).toBe(100);+ });++ it('computes healthy years as 85% of remaining', () => {+ const result = computeDeathClock('1979-07-31', 78.5, 0);+ const expectedHealthy = Math.round(result.yearsRemaining * 0.85 * 10) / 10;+ expect(result.healthyYearsRemaining).toBe(expectedHealthy);+ });+});++// =============================================================================+// LEV TRACKER TESTS+// =============================================================================++describe('computeLEV', () => {+ it('computes on-track status when LE exceeds age at LEV', () => {+ const result = computeLEV('1979-07-31', 80);+ expect(result.targetYear).toBe(2045);+ expect(result.ageAtLEV).toBe(66);+ expect(result.onTrack).toBe(true);+ expect(result.adjustedLifeExpectancy).toBe(80);+ });++ it('computes at-risk status when LE is below age at LEV', () => {+ const result = computeLEV('1979-07-31', 60);+ expect(result.onTrack).toBe(false);+ });++ it('has years to LEV decreasing over time', () => {+ const result = computeLEV('1979-07-31', 80);+ expect(result.yearsToLEV).toBeGreaterThan(0);+ expect(result.yearsToLEV).toBeLessThan(25);+ });++ it('research progress increases over time', () => {+ const result = computeLEV('1979-07-31', 80);+ expect(result.researchProgress).toBeGreaterThan(50);+ expect(result.researchProgress).toBeLessThan(100);+ });+});diff --git a/server/services/meatspaceImport.js b/server/services/meatspaceImport.jsnew file mode 100644index 0000000000..5e60f48270--- /dev/null+++ b/server/services/meatspaceImport.js@@ -0,0 +1,370 @@+/**+ * MeatSpace TSV Import Service+ *+ * Parses the user's health spreadsheet (3 header rows + 2 summary rows + data).+ * Hardcoded column mapping for the specific 257-column layout.+ */++import { writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS, ensureDir } from '../lib/fileUtils.js';++const MEATSPACE_DIR = PATHS.meatspace;+const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');+const BLOOD_TESTS_FILE = join(MEATSPACE_DIR, 'blood-tests.json');+const EPIGENETIC_TESTS_FILE = join(MEATSPACE_DIR, 'epigenetic-tests.json');+const EYES_FILE = join(MEATSPACE_DIR, 'eyes.json');++// Column indices (0-based)+const COL = {+ DATE: 2,+ // Nutrition (3-11)+ CALORIES: 3,+ FAT: 4,+ SAT_FAT: 5,+ TRANS_FAT: 6,+ POLY_FAT: 7,+ MONO_FAT: 8,+ CARBS: 9,+ FIBER: 10,+ SUGAR: 11,+ // Alcohol summary+ ALCOHOL_GRAMS: 12,+ // Body composition (15-20)+ WEIGHT_LBS: 15,+ WEIGHT_KG: 16,+ MUSCLE_PCT: 17,+ FAT_PCT: 18,+ BONE_MASS: 19,+ TEMPERATURE: 20,+ // Protein/Mercury columns (84-112)+ PROTEIN_START: 84,+ PROTEIN_END: 112,+ // Individual beverages (113-172)+ BEVERAGE_START: 113,+ BEVERAGE_END: 172,+ // Elysium Index (173-184)+ EPIGENETIC_START: 173,+ EPIGENETIC_END: 184,+ // Blood tests (185-239)+ BLOOD_START: 185,+ BLOOD_END: 239,+ // Eye prescription (240-245)+ EYE_START: 240,+ EYE_END: 245+};++// Epigenetic field names (indices relative to EPIGENETIC_START)+const EPIGENETIC_FIELDS = [+ 'chronologicalAge', 'biologicalAge', 'paceOfAging',+ 'brain', 'liver', 'metabolic', 'immune', 'hormone',+ 'kidney', 'heart', 'inflammation', 'blood'+];++// Eye field names (indices relative to EYE_START)+const EYE_FIELDS = [+ 'rightSphere', 'rightCylinder', 'rightAxis',+ 'leftSphere', 'leftCylinder', 'leftAxis'+];++// === Parsing Helpers ===++function parseNum(val) {+ if (val === undefined || val === null || val === '' || val === '-') return null;+ const cleaned = String(val).replace(/,/g, '').trim();+ if (!cleaned) return null;+ const n = Number(cleaned);+ return isNaN(n) ? null : n;+}++function parseDate(val) {+ if (!val) return null;+ // Convert YYYY/MM/DD to YYYY-MM-DD+ const cleaned = String(val).trim().replace(/\//g, '-');+ if (!/^\d{4}-\d{2}-\d{2}$/.test(cleaned)) return null;+ return cleaned;+}++function isEmptyRow(cells) {+ return cells.every(c => !c || c.trim() === '' || c.trim() === '-');+}++// === Beverage Parsing ===++function parseBeverages(row, beverageNames, beverageABVs, beverageSizes) {+ const drinks = [];+ let totalStandardDrinks = 0;++ for (let i = COL.BEVERAGE_START; i <= COL.BEVERAGE_END; i++) {+ const count = parseNum(row[i]);+ if (!count || count <= 0) continue;++ const idx = i - COL.BEVERAGE_START;+ const name = beverageNames[idx] || `Beverage ${idx + 1}`;+ const abv = parseNum(beverageABVs[idx]) || 5;+ const servingOz = parseNum(beverageSizes[idx]) || 12;++ const oz = servingOz * count;+ const pureAlcoholOz = oz * (abv / 100);+ const standardDrinks = pureAlcoholOz / 0.6;++ drinks.push({ name, abv, oz, count });+ totalStandardDrinks += standardDrinks;+ }++ return { drinks, standardDrinks: Math.round(totalStandardDrinks * 100) / 100 };+}++// === Mercury from Protein Sources ===++function parseMercury(row, mercuryHeaders) {+ let totalMercuryMg = 0;+ for (let i = COL.PROTEIN_START; i <= COL.PROTEIN_END; i++) {+ const servings = parseNum(row[i]);+ if (!servings || servings <= 0) continue;+ const idx = i - COL.PROTEIN_START;+ const hgMg = parseNum(mercuryHeaders[idx]) || 0;+ totalMercuryMg += servings * hgMg;+ }+ return Math.round(totalMercuryMg * 1000) / 1000 || null;+}++// === Blood Test Parsing ===++function parseBloodTests(row, bloodHeaders) {+ const result = {};+ let hasAny = false;++ for (let i = COL.BLOOD_START; i <= COL.BLOOD_END; i++) {+ const val = parseNum(row[i]);+ if (val === null) continue;+ const idx = i - COL.BLOOD_START;+ const header = (bloodHeaders[idx] || `blood_${idx}`).toLowerCase().replace(/[^a-z0-9]/g, '_');+ result[header] = val;+ hasAny = true;+ }++ return hasAny ? result : null;+}++// === Epigenetic Parsing ===++function parseEpigenetic(row) {+ const result = {};+ let hasAny = false;++ for (let i = 0; i < EPIGENETIC_FIELDS.length; i++) {+ const val = parseNum(row[COL.EPIGENETIC_START + i]);+ if (val === null) continue;+ result[EPIGENETIC_FIELDS[i]] = val;+ hasAny = true;+ }++ if (!hasAny) return null;++ // Separate organ scores from top-level fields+ const organScores = {};+ const topLevel = {};+ const organFields = ['brain', 'liver', 'metabolic', 'immune', 'hormone', 'kidney', 'heart', 'inflammation', 'blood'];+ for (const [key, val] of Object.entries(result)) {+ if (organFields.includes(key)) {+ organScores[key] = val;+ } else {+ topLevel[key] = val;+ }+ }++ return { ...topLevel, organScores };+}++// === Eye Rx Parsing ===++function parseEyes(row) {+ const result = {};+ let hasAny = false;++ for (let i = 0; i < EYE_FIELDS.length; i++) {+ const val = parseNum(row[COL.EYE_START + i]);+ if (val === null) continue;+ result[EYE_FIELDS[i]] = val;+ hasAny = true;+ }++ return hasAny ? result : null;+}++// === Main Import Function ===++export async function importTSV(content) {+ await ensureDir(MEATSPACE_DIR);++ const lines = content.split('\n');+ if (lines.length < 6) {+ return { error: 'TSV file too short. Expected at least 6 rows (3 headers + 2 summaries + data).' };+ }++ // Parse header rows+ const headerRow1 = lines[0].split('\t'); // Category headers+ const headerRow2 = lines[1].split('\t'); // Item names (beverage names, blood test names)+ const headerRow3 = lines[2].split('\t'); // Serving sizes, reference ranges, units++ // Extract beverage metadata from headers+ const beverageNames = [];+ const beverageABVs = [];+ const beverageSizes = [];+ for (let i = COL.BEVERAGE_START; i <= COL.BEVERAGE_END; i++) {+ const idx = i - COL.BEVERAGE_START;+ beverageNames[idx] = headerRow2[i] || '';+ // ABV typically in row 2 header, serving size in row 3+ const abvMatch = String(headerRow2[i] || '').match(/(\d+\.?\d*)%/);+ beverageABVs[idx] = abvMatch ? abvMatch[1] : headerRow3[i];+ beverageSizes[idx] = headerRow3[i] || '12';+ }++ // Extract mercury values from protein source headers (row 3 has Hg mg values)+ const mercuryHeaders = [];+ for (let i = COL.PROTEIN_START; i <= COL.PROTEIN_END; i++) {+ mercuryHeaders[i - COL.PROTEIN_START] = headerRow3[i] || '0';+ }++ // Extract blood test names from row 2+ const bloodHeaders = [];+ for (let i = COL.BLOOD_START; i <= COL.BLOOD_END; i++) {+ bloodHeaders[i - COL.BLOOD_START] = headerRow2[i] || '';+ }++ // Extract blood reference ranges from row 3+ const referenceRanges = {};+ for (let i = COL.BLOOD_START; i <= COL.BLOOD_END; i++) {+ const idx = i - COL.BLOOD_START;+ const header = (bloodHeaders[idx] || '').toLowerCase().replace(/[^a-z0-9]/g, '_');+ const rangeStr = String(headerRow3[i] || '');+ const rangeMatch = rangeStr.match(/([\d.]+)\s*-\s*([\d.]+)/);+ if (rangeMatch && header) {+ referenceRanges[header] = {+ min: parseFloat(rangeMatch[1]),+ max: parseFloat(rangeMatch[2]),+ label: bloodHeaders[idx] || header+ };+ }+ }++ // Data starts at row 5 (0-indexed: rows 0-2 are headers, rows 3-4 are summaries)+ const dailyEntries = [];+ const bloodTests = [];+ const epigeneticTests = [];+ const eyeExams = [];++ for (let lineIdx = 5; lineIdx < lines.length; lineIdx++) {+ const line = lines[lineIdx];+ if (!line.trim()) continue;++ const cells = line.split('\t');+ if (isEmptyRow(cells)) continue;++ const date = parseDate(cells[COL.DATE]);+ if (!date) continue;++ // Nutrition+ const nutrition = {};+ const cal = parseNum(cells[COL.CALORIES]);+ if (cal !== null) nutrition.calories = cal;+ const fat = parseNum(cells[COL.FAT]);+ if (fat !== null) nutrition.fatG = fat;+ const satFat = parseNum(cells[COL.SAT_FAT]);+ if (satFat !== null) nutrition.satFatG = satFat;+ const transFat = parseNum(cells[COL.TRANS_FAT]);+ if (transFat !== null) nutrition.transFatG = transFat;+ const polyFat = parseNum(cells[COL.POLY_FAT]);+ if (polyFat !== null) nutrition.polyFatG = polyFat;+ const monoFat = parseNum(cells[COL.MONO_FAT]);+ if (monoFat !== null) nutrition.monoFatG = monoFat;+ const carbs = parseNum(cells[COL.CARBS]);+ if (carbs !== null) nutrition.carbG = carbs;+ const fiber = parseNum(cells[COL.FIBER]);+ if (fiber !== null) nutrition.fiberG = fiber;+ const sugar = parseNum(cells[COL.SUGAR]);+ if (sugar !== null) nutrition.sugarG = sugar;++ // Body composition+ const body = {};+ const weightLbs = parseNum(cells[COL.WEIGHT_LBS]);+ if (weightLbs !== null) body.weightLbs = weightLbs;+ const weightKg = parseNum(cells[COL.WEIGHT_KG]);+ if (weightKg !== null) body.weightKg = weightKg;+ const musclePct = parseNum(cells[COL.MUSCLE_PCT]);+ if (musclePct !== null) body.musclePct = musclePct;+ const fatPct = parseNum(cells[COL.FAT_PCT]);+ if (fatPct !== null) body.fatPct = fatPct;+ const boneMass = parseNum(cells[COL.BONE_MASS]);+ if (boneMass !== null) body.boneMass = boneMass;+ const temp = parseNum(cells[COL.TEMPERATURE]);+ if (temp !== null) body.temperature = temp;++ // Alcohol+ const alcohol = parseBeverages(cells, beverageNames, beverageABVs, beverageSizes);++ // Mercury+ const mercuryMg = parseMercury(cells, mercuryHeaders);++ // Build daily entry (only include populated sections)+ const entry = { date };+ if (Object.keys(nutrition).length > 0) entry.nutrition = nutrition;+ if (alcohol.drinks.length > 0) entry.alcohol = alcohol;+ if (Object.keys(body).length > 0) entry.body = body;+ if (mercuryMg) entry.mercuryMg = mercuryMg;++ // Only add if entry has data beyond just the date+ if (Object.keys(entry).length > 1) {+ dailyEntries.push(entry);+ }++ // Blood tests (sparse - check if any blood values exist)+ const bloodData = parseBloodTests(cells, bloodHeaders);+ if (bloodData) {+ bloodTests.push({ date, ...bloodData });+ }++ // Epigenetic (sparse)+ const epiData = parseEpigenetic(cells);+ if (epiData) {+ epigeneticTests.push({ date, ...epiData });+ }++ // Eyes (sparse)+ const eyeData = parseEyes(cells);+ if (eyeData) {+ eyeExams.push({ date, ...eyeData });+ }+ }++ // Sort entries by date+ dailyEntries.sort((a, b) => a.date.localeCompare(b.date));+ bloodTests.sort((a, b) => a.date.localeCompare(b.date));+ epigeneticTests.sort((a, b) => a.date.localeCompare(b.date));+ eyeExams.sort((a, b) => a.date.localeCompare(b.date));++ // Write all data files+ const lastEntryDate = dailyEntries.length > 0 ? dailyEntries[dailyEntries.length - 1].date : null;++ await Promise.all([+ writeFile(DAILY_LOG_FILE, JSON.stringify({ entries: dailyEntries, lastEntryDate }, null, 2)),+ writeFile(BLOOD_TESTS_FILE, JSON.stringify({ tests: bloodTests, referenceRanges }, null, 2)),+ writeFile(EPIGENETIC_TESTS_FILE, JSON.stringify({ tests: epigeneticTests }, null, 2)),+ writeFile(EYES_FILE, JSON.stringify({ exams: eyeExams }, null, 2))+ ]);++ const stats = {+ dailyEntries: dailyEntries.length,+ bloodTests: bloodTests.length,+ epigeneticTests: epigeneticTests.length,+ eyeExams: eyeExams.length,+ dateRange: dailyEntries.length > 0+ ? { from: dailyEntries[0].date, to: lastEntryDate }+ : null+ };++ console.log(`📊 MeatSpace import: ${stats.dailyEntries} daily entries, ${stats.bloodTests} blood tests, ${stats.epigeneticTests} epigenetic, ${stats.eyeExams} eye exams`);++ return stats;+}diff --git a/server/services/meatspaceImport.test.js b/server/services/meatspaceImport.test.jsnew file mode 100644index 0000000000..ec643d9bd9--- /dev/null+++ b/server/services/meatspaceImport.test.js@@ -0,0 +1,205 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock fs and fileUtils to avoid actual file I/O+vi.mock('fs/promises', () => ({+ writeFile: vi.fn().mockResolvedValue(undefined),+ readFile: vi.fn().mockResolvedValue('{}')+}));++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { meatspace: '/tmp/test-meatspace' },+ ensureDir: vi.fn().mockResolvedValue(undefined)+}));++import { writeFile } from 'fs/promises';+import { importTSV } from './meatspaceImport.js';++// =============================================================================+// HELPER: Build TSV content+// =============================================================================++function buildTSV({ headerRow1, headerRow2, headerRow3, summaryRow1, summaryRow2, dataRows }) {+ return [headerRow1, headerRow2, headerRow3, summaryRow1, summaryRow2, ...dataRows].join('\n');+}++function makeEmptyHeaders(count) {+ return new Array(count).fill('').join('\t');+}++// Build a minimal TSV with just date and nutrition columns+function buildMinimalTSV(dataRows) {+ // Columns: 0=empty, 1=empty, 2=date, 3=cal, 4=fat, 5=satFat, 6=transFat, 7=polyFat, 8=monoFat, 9=carb, 10=fiber, 11=sugar+ const colCount = 250;+ const row1 = makeEmptyHeaders(colCount);+ const row2 = makeEmptyHeaders(colCount);+ const row3 = makeEmptyHeaders(colCount);+ const sum1 = makeEmptyHeaders(colCount);+ const sum2 = makeEmptyHeaders(colCount);++ const rows = dataRows.map(row => {+ const cells = new Array(colCount).fill('');+ if (row.date) cells[2] = row.date;+ if (row.calories != null) cells[3] = String(row.calories);+ if (row.fat != null) cells[4] = String(row.fat);+ if (row.carbs != null) cells[9] = String(row.carbs);+ if (row.fiber != null) cells[10] = String(row.fiber);+ if (row.sugar != null) cells[11] = String(row.sugar);+ // Body+ if (row.weightLbs != null) cells[15] = String(row.weightLbs);+ if (row.weightKg != null) cells[16] = String(row.weightKg);+ return cells.join('\t');+ });++ return buildTSV({+ headerRow1: row1,+ headerRow2: row2,+ headerRow3: row3,+ summaryRow1: sum1,+ summaryRow2: sum2,+ dataRows: rows+ });+}++// =============================================================================+// TESTS+// =============================================================================++describe('importTSV', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('rejects files with fewer than 6 lines', async () => {+ const result = await importTSV('line1\nline2\nline3');+ expect(result.error).toMatch(/too short/i);+ });++ it('parses daily entries with nutrition data', async () => {+ const tsv = buildMinimalTSV([+ { date: '2024/01/15', calories: 1500, fat: 65, carbs: 180, fiber: 25, sugar: 40 },+ { date: '2024/01/16', calories: 1800, fat: 70, carbs: 200 }+ ]);++ const result = await importTSV(tsv);+ expect(result.dailyEntries).toBe(2);+ expect(result.dateRange.from).toBe('2024-01-15');+ expect(result.dateRange.to).toBe('2024-01-16');++ // Check that writeFile was called with parsed data+ const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));+ expect(dailyLogCall).toBeTruthy();++ const dailyLog = JSON.parse(dailyLogCall[1]);+ expect(dailyLog.entries).toHaveLength(2);+ expect(dailyLog.entries[0].date).toBe('2024-01-15');+ expect(dailyLog.entries[0].nutrition.calories).toBe(1500);+ expect(dailyLog.entries[0].nutrition.fatG).toBe(65);+ expect(dailyLog.entries[0].nutrition.carbG).toBe(180);+ expect(dailyLog.entries[0].nutrition.fiberG).toBe(25);+ expect(dailyLog.entries[0].nutrition.sugarG).toBe(40);+ });++ it('converts YYYY/MM/DD date format to YYYY-MM-DD', async () => {+ const tsv = buildMinimalTSV([+ { date: '2023/02/04', calories: 1000 }+ ]);++ const result = await importTSV(tsv);+ expect(result.dailyEntries).toBe(1);++ const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));+ const dailyLog = JSON.parse(dailyLogCall[1]);+ expect(dailyLog.entries[0].date).toBe('2023-02-04');+ });++ it('parses body composition data', async () => {+ const tsv = buildMinimalTSV([+ { date: '2024/03/10', weightLbs: 158, weightKg: 71.67 }+ ]);++ const result = await importTSV(tsv);+ expect(result.dailyEntries).toBe(1);++ const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));+ const dailyLog = JSON.parse(dailyLogCall[1]);+ expect(dailyLog.entries[0].body.weightLbs).toBe(158);+ expect(dailyLog.entries[0].body.weightKg).toBe(71.67);+ });++ it('skips rows without valid dates', async () => {+ const tsv = buildMinimalTSV([+ { date: '', calories: 500 },+ { date: 'invalid', calories: 600 },+ { date: '2024/01/01', calories: 700 }+ ]);++ const result = await importTSV(tsv);+ expect(result.dailyEntries).toBe(1);+ });++ it('skips empty data rows', async () => {+ const tsv = buildMinimalTSV([+ { date: '2024/01/01', calories: 700 },+ { date: '2024/01/02' } // No data besides date+ ]);++ const result = await importTSV(tsv);+ expect(result.dailyEntries).toBe(1);+ });++ it('sorts entries by date', async () => {+ const tsv = buildMinimalTSV([+ { date: '2024/03/15', calories: 1500 },+ { date: '2024/01/10', calories: 1200 },+ { date: '2024/02/20', calories: 1800 }+ ]);++ const result = await importTSV(tsv);+ expect(result.dailyEntries).toBe(3);++ const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));+ const dailyLog = JSON.parse(dailyLogCall[1]);+ expect(dailyLog.entries[0].date).toBe('2024-01-10');+ expect(dailyLog.entries[1].date).toBe('2024-02-20');+ expect(dailyLog.entries[2].date).toBe('2024-03-15');+ });++ it('handles dash and empty values as null', async () => {+ const colCount = 250;+ const row1 = makeEmptyHeaders(colCount);+ const row2 = makeEmptyHeaders(colCount);+ const row3 = makeEmptyHeaders(colCount);+ const sum1 = makeEmptyHeaders(colCount);+ const sum2 = makeEmptyHeaders(colCount);++ const cells = new Array(colCount).fill('');+ cells[2] = '2024/01/01';+ cells[3] = '1000'; // calories+ cells[4] = '-'; // fat = dash+ cells[9] = ''; // carbs = empty++ const tsv = [row1, row2, row3, sum1, sum2, cells.join('\t')].join('\n');+ const result = await importTSV(tsv);+ expect(result.dailyEntries).toBe(1);++ const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));+ const dailyLog = JSON.parse(dailyLogCall[1]);+ expect(dailyLog.entries[0].nutrition.calories).toBe(1000);+ expect(dailyLog.entries[0].nutrition.fatG).toBeUndefined();+ expect(dailyLog.entries[0].nutrition.carbG).toBeUndefined();+ });++ it('writes all four output files', async () => {+ const tsv = buildMinimalTSV([+ { date: '2024/01/01', calories: 1000 }+ ]);++ await importTSV(tsv);++ const fileNames = writeFile.mock.calls.map(c => c[0]);+ expect(fileNames.some(f => f.includes('daily-log.json'))).toBe(true);+ expect(fileNames.some(f => f.includes('blood-tests.json'))).toBe(true);+ expect(fileNames.some(f => f.includes('epigenetic-tests.json'))).toBe(true);+ expect(fileNames.some(f => f.includes('eyes.json'))).toBe(true);+ });+});