Comments: trim to the established cadence
The MCP code came in with 5–8 line file headers, JSDoc on every
one-line wrapper, and inline explanations that referenced the PR
itself ("so the MCP server can reuse it") — none of which matches
api/server.js or frontend/src/lib/, where comments are one-line,
fact-shaped and never mention the change that introduced them.
Trimmed across mcp/src/*.js, i18n-core.js, i18n.js, exercises.js,
format.js, mcp/test/tools.test.js, mcp/vitest.config.js and
mcp/README.md. Tool prefaces lost their numbers; duplicate fs.watch
rationale folded into one; the ASCII import diagram in the README
replaced with a paragraph; the cross-references and self-references
removed. Also fixed two real defects: a corrupted Cyrillic word in a
state.js comment and a missing space in a tools.test.js comment.
No code changes; 92 frontend + 32 MCP tests still pass.
This commit is contained in:
1 parent
4143ab8676
commit
6aaf2a3eea
11 files changed
+93
-245
No files matched your search
+16
-43
@@ -1,24 +1,18 @@
|
||||
// State accessor — opens ./data/state-<uid>.json (+ db.json for the user record), caches it,
|
||||
// and re-reads via fs.watch so tools reflect a session the web UI just finished without a
|
||||
// server restart. Read-only by design: nothing in the MCP server ever writes to these files,
|
||||
// which keeps it consistent with the api server's own read-on-write view of state.
|
||||
//
|
||||
// The state shape comes straight from frontend/src/store/useStore.js DEF; the runtime fields
|
||||
// that stay device-local (`active`) never reach the file — see api server.js PUT /api/data.
|
||||
/* opengym-mcp state — reads ./data/state-<uid>.json + db.json (read-only). Cached with an
|
||||
fs.watch + mtime fallback so a session the api server just wrote is visible on the next
|
||||
tool call without a restart. */
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
const DATA_DIR = process.env.OPENGYM_DATA || path.join(process.cwd(), 'data')
|
||||
|
||||
// Cached state. `null` means "no state file for this user" (e.g. brand-new account that never
|
||||
// signed in on a device). `undefined` means "not yet loaded".
|
||||
// null = no state file (brand-new account); undefined = not yet loaded.
|
||||
let _state = undefined
|
||||
let _db = undefined
|
||||
let _uid = null
|
||||
let _watcher = null
|
||||
let _loadedMtime = 0 // mtimeMs we last read at — used to catch watcher omissions
|
||||
|
||||
/** A safe read of a JSON file; returns null on missing/invalid rather than throwing. */
|
||||
function readJsonOrNull(file) {
|
||||
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
|
||||
}
|
||||
@@ -29,18 +23,9 @@ function stateFile(uid) {
|
||||
return path.join(DATA_DIR, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json')
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve which user the MCP server should answer for.
|
||||
*
|
||||
* Strategy, in order:
|
||||
* 1. OPENGYM_UID env — explicit choice on multi-user instances.
|
||||
* 2. Exactly one state file in ./data — the common self-hosted single-user case.
|
||||
* 3. Exactly one user in db.json with no state file yet — same intent, brand-new account.
|
||||
* 4. Otherwise: throw with the list of options so the user can pick.
|
||||
*
|
||||
* The uid pattern `^[a-zA-Z0-9_-]+$` matches what api/server.js emits (base64url of 12 random
|
||||
* bytes), and the sanitise on stateFile() above keeps a sneaky `..` in OPENGYM_UID harmless.
|
||||
*/
|
||||
// Pick the uid: OPENGYM_UID env, else the only state-* file, else the only user in db.json.
|
||||
// Throws listing the options if ambiguous. The sanitiser on stateFile() keeps a sneaky
|
||||
// '..' in OPENGYM_UID harmless.
|
||||
function resolveUid() {
|
||||
const envUid = (process.env.OPENGYM_UID || '').trim()
|
||||
if (envUid) {
|
||||
@@ -62,9 +47,9 @@ function resolveUid() {
|
||||
)
|
||||
}
|
||||
|
||||
/** Set up the live state view: pick the uid, load db.json, attach the watcher, prime state. */
|
||||
// Idempotent. Picks the uid, loads db.json, attaches the watcher, primes state.
|
||||
export function init() {
|
||||
if (_uid !== null) return // idempotent
|
||||
if (_uid !== null) return
|
||||
if (!fs.existsSync(DATA_DIR)) throw new Error(`OPENGYM_DATA dir does not exist: ${DATA_DIR}`)
|
||||
_uid = resolveUid()
|
||||
reloadDb()
|
||||
@@ -75,11 +60,8 @@ export function init() {
|
||||
try { _loadedMtime = fs.statSync(file).mtimeMs } catch {}
|
||||
}
|
||||
if (_watcher) _watcher.close()
|
||||
// fs.watch is best-effort: the watcher may briefly drop events under some filesystems, but
|
||||
// its purpose is responsiveness (a tool call mid- ещё-one-sync), not durability — the api
|
||||
// server's atomic write at PUT /api/data is the source of truth, and a stale read just gets
|
||||
// corrected on the next change or the next tool call. We still re-read in getState() if the
|
||||
// cached state is older than the file's mtime — covers the worst case of a missed event.
|
||||
// fs.watch is best-effort: the api server's atomic write at PUT /api/data is the source of
|
||||
// truth, and a stale read just gets corrected on the next change or the next tool call.
|
||||
try {
|
||||
_watcher = fs.watch(file, () => {
|
||||
// On change, simply clear the cache — the next getState() will re-read. Avoids reading
|
||||
@@ -90,17 +72,14 @@ export function init() {
|
||||
} catch { /* fs.watch unsupported on this platform; tools will re-read on mtime change */ }
|
||||
}
|
||||
|
||||
/** Returns the state object (or null for a fresh account), re-reading on mtime change. */
|
||||
// Returns the state object, or null for a fresh account that never signed in on a device.
|
||||
export function getState() {
|
||||
init()
|
||||
const file = stateFile(_uid)
|
||||
// fs.watch's reliability varies by filesystem — we still re-read whenever the file's mtime
|
||||
// has changed since our last load. This covers watcher omissions, no-watcher platforms, and
|
||||
// a call landed in the brief gap between the api server's atomic write and our event firing.
|
||||
// Re-read if the file's mtime changed since our last load — covers watcher omissions and
|
||||
// platforms with no fs.watch.
|
||||
let mtime
|
||||
try { mtime = fs.statSync(file).mtimeMs } catch {
|
||||
// File no longer exists (account deleted since boot). Return what we have if anything;
|
||||
// the caller handles null/undefined same as a fresh account.
|
||||
return _state === undefined ? null : _state
|
||||
}
|
||||
if (_state === undefined || mtime !== _loadedMtime) {
|
||||
@@ -117,21 +96,16 @@ export function getState() {
|
||||
return _state
|
||||
}
|
||||
|
||||
/** The user record (id + name) from db.json. Excludes passkeys/credentials and push subs. */
|
||||
// Returns the user record (id + name). No passkey material, no VAPID keys, no push subs.
|
||||
export function getUser() {
|
||||
init()
|
||||
const u = _db.users.find(x => x.id === _uid) || { id: _uid, name: 'Profile', created: null }
|
||||
return { id: u.id, name: u.name, created: u.created || null }
|
||||
}
|
||||
|
||||
/** Path to the data dir (debug/test hook). */
|
||||
export const dataDir = () => DATA_DIR
|
||||
|
||||
/**
|
||||
* Test-only escape hatch: work against a passed-in state object instead of reading disk.
|
||||
* The MCP server is read-only, so tests don't need to write files — pass any state object
|
||||
* (typically from frontend/src/lib/demoSeed.js buildDemoState()) and the tools will use it.
|
||||
*/
|
||||
// Test-only: work against a passed-in state, not the disk.
|
||||
export function _seedStateForTests(state) {
|
||||
_uid = 'test-uid'
|
||||
_db = { users: [{ id: _uid, name: 'Test', created: '2026-07-26T00:00:00.000Z' }], creds: [], subs: [], invites: [] }
|
||||
@@ -140,7 +114,6 @@ export function _seedStateForTests(state) {
|
||||
if (_watcher) { _watcher.close(); _watcher = null }
|
||||
}
|
||||
|
||||
/** The minimum shape the tools assume — fields default to empty/none if absent. */
|
||||
function defaultsShape() {
|
||||
return {
|
||||
unit: 'kg', restSec: 90, sound: true, lang: 'en',
|
||||
|
||||
Reference in new issue
Block a user