fix: repair DASH-001 live session state and readiness panel

This commit is contained in:
2026-08-17 10:47:53 -04:00
parent 8ca000a166
commit e7b6ae5878
7 changed files with 251 additions and 15 deletions

View File

@@ -27,6 +27,7 @@
- Approved: 2026-08-10 (Mo).
- Related: `docs/IDEAS_BACKLOG.md` (n8n AM Briefing — related but separate item), `NT8_SDK_Master_Document` Appendix B (Command Center spec — source of feature inspiration for external version).
- **Extension (2026-08-16):** Add outbound notification module to the dashboard's Python server (NOT to the NinjaScript strategy) using Apprise for unified Discord/Notifiarr/ntfy/etc. delivery. Alerts on FILL, SUBMIT, BREAKEVEN, CONNECTION LOST/RESTORED, daily P&L milestones. Bind server to 127.0.0.1 only, read-only endpoints, no POST/write routes. Poll interval must be explicit/configurable: 1-2s for live session-log tail, 5-10s for trades table/config panel.
- **Bugfix/Extension (2026-08-17):** Live server current-session selection now uses newest root-level `session_*.log` by file modification time and populates `current_session` even when notification offsets start at EOF. Dashboard adds a Bars/Days-Loaded panel from existing Historical readiness and FactorWarmup log lines.
**[DASH-002] Continuous Confluence & Regime Telemetry** | Weekend window 2026-08-16 | 🔵 ACTIVE
- Scope: `src\` source change — adds `EnableStateTelemetry` parameter emitting periodic factor/regime state to session log (currently only logged at signal time). Additive observability only; existing SIGNAL/SUBMIT/FILL/PNL_UPDATE lines must remain byte-for-byte unaffected.

View File

@@ -0,0 +1,49 @@
# TASK: DASH-001 Bugfix + Bars/Days-Loaded Panel
# Staged: 2026-08-17
# Sprint: Parallel Product Work — dashboard-only, safe while gate strategy is armed
# ─────────────────────────────────────────────────────────────────
## Part 1 — BUGFIX (priority, ship first)
dashboard_state.json currently shows offsets tracked for 16 session log files,
including the most recent (session_20260817_100812.log), but `current_session`
remains `null`. This is why the Live Local Server UI shows no live trade/
confluence/P&L data despite the server correctly polling files.
READ-FIRST: locate the logic in server.py/state.py responsible for selecting
the "current" session log. It should be the most recently created/modified
session_*.log in the configured log directory. Identify why it's tracking
offsets (proving it opens and reads these files) but never assigns to
current_session.
Also account for this real scenario from today's actual log directory: SIX
session_*.log files were created within a 90-second window this morning
(08:20:19 through 08:21:03), i.e. six rapid strategy restarts. Confirm
selection logic picks the newest by file mtime, not by filename string
comparison alone (verify these don't collide/misorder).
FIX: ensure `current_session` populates reliably on every poll cycle,
including correctly re-pointing to a new session file when NT8 restarts
mid-day.
VALIDATE: restart the dashboard server against the live log directory and
confirm current_session populates, and that trade/P&L/connection data from
the most recent real session (including any overnight session) appears in
the UI without a manual reload or restart.
## Part 2 — Bars/Days-Loaded Panel
Add a new dashboard panel showing, from the current session's log:
- Per-series: Type, DaysToLoad, HistoricalBarsLoaded (from the
"DataSeries[N] : Type=... DaysToLoad=... HistoricalBarsLoaded=..." lines)
- Factor warm-up status per calculator (from the "FactorWarmup : ..."
line) — display as pass/fail per calculator (e.g.
NarrowRangeFactorCalculator: SATISFIED 86/7, OrbRangeVsAtrFactorCalculator:
SATISFIED 86/5), not just the raw log line.
This data is already written once per session at startup — no NT8 source
change needed. Parse the existing "Historical readiness" block from
parsers.py the same way FILL/PNL_UPDATE/etc. are already parsed.
## GOVERNANCE
Track both under [DASH-001] in SPRINT_BOARD.md (extension, not a new item).

View File

@@ -661,6 +661,33 @@
renderTable("config-table", ["Date", "ConfigHash", "Hash(8)", "CodeVersion", "Drift"], rows);
}
function renderReadiness(readiness) {
readiness = readiness || {};
setTextIfPresent("readiness-context", readiness.context || "No Historical readiness block found in the current session tail.");
var seriesRows = asArray(readiness.data_series).map(function (item) {
return [
display(item.index),
display(item.type),
display(item.days_to_load),
display(item.historical_bars_loaded)
];
});
renderTable("readiness-series-table", ["Series", "Type", "DaysToLoad", "HistoricalBarsLoaded"], seriesRows);
var factorRows = asArray(readiness.factors).map(function (item) {
var status = String(item.status || "").toUpperCase();
var pillClass = status === "SATISFIED" ? "good" : "bad";
return [
display(item.name),
{ html: '<span class="pill ' + pillClass + '">' + display(status || "-") + '</span>' },
display(item.loaded),
display(item.required),
item.loaded !== undefined && item.required !== undefined ? display(item.loaded) + " / " + display(item.required) : "-"
];
});
renderTable("readiness-factor-table", ["Calculator", "Status", "Loaded", "Required", "Ratio"], factorRows);
}
function render(payload, label) {
var data = normalize(payload);
renderHeadline(data);
@@ -683,6 +710,8 @@
setTextIfPresent("live-pnl", live.daily_pnl !== undefined ? String(live.daily_pnl) : "-");
setTextIfPresent("live-position", live.position ? live.position + " " + (live.quantity !== undefined ? live.quantity : "") : "-");
setTextIfPresent("live-notify", notify.enabled ? (notify.available ? "enabled" : "unavailable") : "disabled");
setTextIfPresent("live-session-key", payload.current_session || "-");
renderReadiness(payload.readiness || {});
var rawTail = document.getElementById("raw-tail");
if (rawTail) {
rawTail.textContent = asArray(payload.raw_tail).slice(-80).join("\n");

View File

@@ -68,6 +68,28 @@
<small>Apprise status</small>
</article>
</div>
<section class="readiness-panel" aria-labelledby="readiness-title">
<div class="section-title">
<div>
<h3 id="readiness-title">Bars / Days Loaded</h3>
<p id="readiness-context" class="panel-note">Read from the current session's Historical readiness block.</p>
</div>
<div class="readiness-meta">
<span>Current session</span>
<strong id="live-session-key">-</strong>
</div>
</div>
<div class="split-grid readiness-grid">
<article>
<h4>Data Series</h4>
<div class="table-wrap"><table id="readiness-series-table"></table></div>
</article>
<article>
<h4>Factor Warm-Up</h4>
<div class="table-wrap"><table id="readiness-factor-table"></table></div>
</article>
</div>
</section>
<pre id="raw-tail" class="raw-tail"></pre>
</section>

View File

@@ -21,7 +21,14 @@ FILL_RE = re.compile(r"\bFILL\b\s+(Long|Short)\s+(\d+)\s+@\s+([0-9.]+)", re.IGNO
BREAKEVEN_RE = re.compile(r"\bBREAKEVEN\b\s*(.*)$", re.IGNORECASE)
RUNNER_CLOSED_RE = re.compile(r"RUNNER closed", re.IGNORECASE)
CONNECTION_RE = re.compile(r"CONNECTION\s+(LOST|RESTORED)", re.IGNORECASE)
CONNECTION_STATE_RE = re.compile(r"^ConnectionLost\s*:\s*(True|False)$", re.IGNORECASE)
PNL_RE = re.compile(r"PNL_UPDATE\s+DayPnL=([^\s]+)\s+Position=([^\s]+)\s+Qty=(\d+)", re.IGNORECASE)
ACCOUNT_RE = re.compile(r"^Account\s*:\s*(.+)$", re.IGNORECASE)
SYMBOL_RE = re.compile(r"^Symbol\s*:\s*(.+)$", re.IGNORECASE)
MODE_RE = re.compile(r"^Mode\s*:\s*(.+)$", re.IGNORECASE)
DATA_SERIES_RE = re.compile(r"DataSeries\[(\d+)\]\s*:\s*Type=([^\s]+)\s+DaysToLoad=([^\s]+)\s+HistoricalBarsLoaded=([^\s]+)", re.IGNORECASE)
FACTOR_WARMUP_RE = re.compile(r"FactorWarmup\s*:\s*(.*)$", re.IGNORECASE)
FACTOR_STATUS_RE = re.compile(r"([A-Za-z0-9_]+)=(SATISFIED|FAILED|UNSATISFIED)\s*\((\d+)/(\d+)\s+daily bars\)", re.IGNORECASE)
def expand_path(raw_path: str) -> Path:
@@ -29,17 +36,29 @@ def expand_path(raw_path: str) -> Path:
def newest_session_file(log_dir: Path) -> Optional[Path]:
newest: Optional[Tuple[datetime, Path]] = None
for path in log_dir.rglob("session_*.log") if log_dir.exists() else []:
newest: Optional[Tuple[float, str, Path]] = None
for path in log_dir.glob("session_*.log") if log_dir.exists() else []:
if not path.is_file():
continue
match = SESSION_FILE_RE.match(path.name)
if match is None:
continue
stamp = datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), "%Y%m%d_%H%M%S")
if newest is None or stamp > newest[0]:
newest = (stamp, path)
return newest[1] if newest else None
try:
mtime = path.stat().st_mtime
except OSError:
continue
if newest is None or (mtime, path.name) > (newest[0], newest[1]):
newest = (mtime, path.name, path)
return newest[2] if newest else None
def session_key(path: Path, lines: List[str]) -> str:
for line in lines:
timestamp, message = split_log_line(line)
start = SESSION_START_RE.search(message)
if start:
return start.group(1)
return path.stem
def newest_matching(log_dir: Path, pattern: str, regex: re.Pattern[str]) -> Optional[Path]:
@@ -129,15 +148,77 @@ def parse_session_event(path: Path, line: str) -> Optional[Dict[str, Any]]:
payload.update({"type": "CONNECTION {0}".format(connection.group(1).upper()), "status": connection.group(1).upper()})
return payload
connection_state = CONNECTION_STATE_RE.search(message)
if connection_state:
payload = dict(base)
payload.update({"type": "CONNECTION STATE", "status": "LOST" if connection_state.group(1).lower() == "true" else "OK"})
return payload
pnl = PNL_RE.search(message)
if pnl:
payload = dict(base)
payload.update({"type": "PNL_UPDATE", "daily_pnl": parse_money(pnl.group(1)), "position": pnl.group(2), "quantity": int(pnl.group(3))})
return payload
account = ACCOUNT_RE.search(message)
if account:
payload = dict(base)
payload.update({"type": "ACCOUNT", "account": account.group(1).strip()})
return payload
symbol = SYMBOL_RE.search(message)
if symbol:
payload = dict(base)
payload.update({"type": "SYMBOL", "symbol": symbol.group(1).strip()})
return payload
mode = MODE_RE.search(message)
if mode:
payload = dict(base)
payload.update({"type": "MODE", "mode": mode.group(1).strip()})
return payload
return None
def parse_readiness(lines: List[str]) -> Dict[str, Any]:
data_series: Dict[int, Dict[str, Any]] = {}
factors: Dict[str, Dict[str, Any]] = {}
context = ""
bars_required = ""
for line in lines:
timestamp, message = split_log_line(line)
if message.startswith("Historical readiness"):
context = message
required = re.search(r"BarsRequiredToTrade=([^\s]+)", message, re.IGNORECASE)
if required:
bars_required = required.group(1)
data_match = DATA_SERIES_RE.search(message)
if data_match:
index = int(data_match.group(1))
data_series[index] = {
"index": index,
"type": data_match.group(2),
"days_to_load": data_match.group(3),
"historical_bars_loaded": data_match.group(4),
}
warmup = FACTOR_WARMUP_RE.search(message)
if warmup:
for factor in FACTOR_STATUS_RE.finditer(warmup.group(1)):
factors[factor.group(1)] = {
"name": factor.group(1),
"status": factor.group(2).upper(),
"loaded": int(factor.group(3)),
"required": int(factor.group(4)),
}
return {
"context": context,
"bars_required_to_trade": bars_required,
"data_series": [data_series[index] for index in sorted(data_series.keys())],
"factors": [factors[name] for name in sorted(factors.keys())],
}
def read_new_complete_lines(path: Path, offset: int, partial: str) -> Tuple[List[str], int, str]:
try:
size = path.stat().st_size

View File

@@ -71,6 +71,7 @@ class DashboardRuntime:
self.provenance: Optional[Dict[str, Any]] = None
self.settings: Dict[str, str] = {}
self.raw_tail: List[str] = []
self.readiness: Dict[str, Any] = {}
self.current_session_file: Optional[str] = None
self.polling = config.get("polling", {}) if isinstance(config.get("polling", {}), dict) else {}
self.session_poll_seconds = float(self.polling.get("session_log_seconds", 2))
@@ -92,7 +93,9 @@ class DashboardRuntime:
return {
"log_dir": str(self.log_dir),
"session_file": self.current_session_file,
"current_session": self.state.current_session,
"live_state": self.live_state,
"readiness": dict(self.readiness),
"events": list(self.latest_events[-100:]),
"trades": list(self.trades),
"provenance": self.provenance,
@@ -122,6 +125,14 @@ class DashboardRuntime:
path = parsers.newest_session_file(self.log_dir)
if path is None:
return
raw_tail = parsers.tail_lines(path)
session_key = parsers.session_key(path, raw_tail)
self.state.rollover_session(session_key)
with self.lock:
self.raw_tail = raw_tail
self.current_session_file = str(path)
self.readiness = parsers.parse_readiness(raw_tail)
self._refresh_live_state_from_tail(path, raw_tail)
offset = self.state.get_offset(path)
if offset is None:
try:
@@ -134,14 +145,18 @@ class DashboardRuntime:
lines, next_offset, next_partial = parsers.read_new_complete_lines(path, offset, partial)
self.state.set_offset(path, next_offset)
self.state.set_partial(path, next_partial)
self.raw_tail = parsers.tail_lines(path)
self.current_session_file = str(path)
for line in lines:
event = parsers.parse_session_event(path, line)
if event is not None:
self._handle_event(event)
self.state.save()
def _refresh_live_state_from_tail(self, path: Path, lines: List[str]) -> None:
for line in lines:
event = parsers.parse_session_event(path, line)
if event is not None:
self._apply_event(event)
def _poll_trades(self) -> None:
path = parsers.today_trades_file(self.log_dir)
trades = parsers.read_trades(path)
@@ -158,16 +173,32 @@ class DashboardRuntime:
self.settings = settings
def _handle_event(self, event: Dict[str, Any]) -> None:
self._apply_event(event)
if str(event.get("type") or "") == "PNL_UPDATE":
self._handle_pnl_milestones(event)
with self.lock:
self.latest_events.append(event)
self.latest_events = self.latest_events[-500:]
self._notify_event(event)
def _apply_event(self, event: Dict[str, Any]) -> None:
event_type = str(event.get("type") or "")
if event_type == "SESSION START":
session_key = str(event.get("session_start") or event.get("source") or "unknown")
self.state.rollover_session(session_key)
self.live_state["session_start"] = event.get("session_start")
elif event_type == "ACCOUNT":
self.live_state["account"] = event.get("account")
elif event_type == "SYMBOL":
self.live_state["symbol"] = event.get("symbol")
elif event_type == "MODE":
self.live_state["mode"] = event.get("mode")
elif event_type == "PNL_UPDATE":
self.live_state["daily_pnl"] = event.get("daily_pnl")
self.live_state["position"] = event.get("position")
self.live_state["quantity"] = event.get("quantity")
self._handle_pnl_milestones(event)
elif event_type.startswith("CONNECTION"):
self.live_state["connection"] = event.get("status")
elif event_type == "FILL":
@@ -177,12 +208,6 @@ class DashboardRuntime:
elif event_type == "BREAKEVEN":
self.live_state["last_breakeven"] = event
with self.lock:
self.latest_events.append(event)
self.latest_events = self.latest_events[-500:]
self._notify_event(event)
def _handle_pnl_milestones(self, event: Dict[str, Any]) -> None:
if not notifications_enabled(self.config, "daily_pnl_milestones"):
return

View File

@@ -228,6 +228,34 @@ tr.status-violation td:first-child { border-left: 0.35rem solid var(--bad); }
white-space: pre-wrap;
}
.readiness-panel {
background: rgba(13, 17, 23, 0.55);
border: 1px solid var(--line);
border-radius: 0.8rem;
margin: 1rem 0;
padding: 1rem;
}
.readiness-panel h3,
.readiness-panel h4 {
margin-bottom: 0.35rem;
}
.readiness-grid {
margin-top: 0.75rem;
}
.readiness-meta {
color: var(--muted);
display: grid;
gap: 0.2rem;
text-align: right;
}
.readiness-meta strong {
color: var(--text);
}
.headline-panel {
border-color: rgba(116, 211, 255, 0.38);
}
@@ -389,4 +417,5 @@ tr.status-violation td:first-child { border-left: 0.35rem solid var(--bad); }
.health-strip { grid-template-columns: repeat(5, 1fr); }
.reason-row { grid-template-columns: 1fr; }
.section-title { display: block; }
.readiness-meta { margin-top: 0.75rem; text-align: left; }
}