Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Stock analysis, screening, and backtesting live in the shared Python CLIs under
3. **Work in verifiable units.** For multi-step work, set the dependency order and verification check for each unit before editing, and verify each unit before building on it. Follow [ponytail](https://github.com/DietrichGebert/ponytail) by reusing [scripts/tool-calls.mjs](scripts/tool-calls.mjs), [scripts/venv-python.mjs](scripts/venv-python.mjs), [tools/_subproc.py](tools/_subproc.py), and [tests/conftest.py](tests/conftest.py) instead of adding parallel helpers or dependencies.
4. **Prove the change.** Rerun the failing reproduction and exercise the real affected entry point. Report the exact commands, observed results, and the host, OS, install mode, or artifact checked. When a target such as Windows, macOS, or an installed host is unavailable, run the nearest local check and state what remains unverified.

When the external [Matt Pocock skills](https://github.com/mattpocock/skills) are installed locally, use `diagnosing-bugs` for regressions, `tdd` for Python behavior changes, and `to-spec` with `to-tickets` for breaking or multi-phase changes. Keep specs, review notes, and external skill files out of commits.
When the external [Matt Pocock skills](https://github.com/mattpocock/skills) are installed locally, use `diagnosing-bugs` for regressions, `tdd` for Python behavior changes, and `to-spec` with `to-tickets` for breaking or multi-phase changes. When the [pstack skills](https://github.com/cursor/plugins/tree/main/pstack/) are installed locally, use `benchmark-checklist` and `principle-explain-the-number` before trusting or reporting performance measurements (name the limiter from profiles or counters, verify outputs and error counts, and report run count, median, and range), and use `blast-radius` for cross-cutting changes alongside `principle-fix-root-causes`, `principle-subtract-before-you-add`, and `principle-prove-it-works`. Keep specs, review notes, and external skill files out of commits.

## Local setup and verification

Expand Down
106 changes: 91 additions & 15 deletions dsh/dashboard.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { accessSync, constants, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { randomUUID } from "node:crypto";
import { createHash, randomUUID } from "node:crypto";
import type { IncomingMessage, ServerResponse } from "node:http";
import type { Context } from "@deepseek-ai/cordis";

Expand Down Expand Up @@ -233,8 +233,10 @@ interface Job {
/** Small priority queue so a burst of trend/stat work never delays quotes. */
function createPriorityLimiter(limit: number) {
let active = 0;
let held = 0;
const waiting: Array<{ priority: number; start: () => void; cancel: () => void }> = [];
const next = () => {
if (held > 0) return;
while (active < limit && waiting.length) {
waiting.sort((a, b) => a.priority - b.priority);
active++;
Expand All @@ -252,6 +254,11 @@ function createPriorityLimiter(limit: number) {
next();
});
},
/** Defer dispatch while a scheduling turn enqueues batched and unbatched jobs together. */
hold<T>(fn: () => T): T {
held++;
try { return fn(); } finally { held--; next(); }
},
/** Settle queued jobs without starting them. */
clear() { for (const job of waiting.splice(0)) job.cancel(); },
get queued() { return waiting.length + active; },
Expand Down Expand Up @@ -342,7 +349,8 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
});
}
function flushBatch(command: "quotes" | "klines", key: string) {
const batch = pendingBatches.get(key)!;
const batch = pendingBatches.get(key);
if (!batch) return;
pendingBatches.delete(key);
const args = [command, batch.map(item => item.symbol).join(","), ...(command === "klines" ? ["--count", "30"] : ["--watchlist"])];
// The CLI times out slow rows itself after 30 s, so one hung provider cannot fail the whole batch.
Expand All @@ -357,10 +365,12 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
}

function quoteJob(symbol: string, priority: number): Job {
const region = watchRegion(symbol);
return {
key: `quote:${symbol}`, kind: "quote", region: watchRegion(symbol), priority, batched: true,
key: `quote:${symbol}`, kind: "quote", region, priority, batched: true,
// Per-region batches: slow overseas/fund/advisor quotes must not hold up A-share quotes.
run: async () => {
const value = await batched("quotes", "all", symbol, priority) as Record<string, unknown> | null;
const value = await batched("quotes", region, symbol, priority) as Record<string, unknown> | null;
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("报价数据格式不正确");
if (value.error) throw new Error(safeError(value.error, "报价暂不可用"));
return { ...value, symbol };
Expand Down Expand Up @@ -388,8 +398,10 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
list.push({
key: `phase:${region}`, kind: "phase", region, priority: 0,
run: async () => {
const value = await py("trading_calendar.py", ["phase", region.toUpperCase()], 10_000) as Record<string, unknown>;
if (!value || typeof value !== "object" || value.error) throw new Error("交易阶段暂不可用");
const value = await py("trading_calendar.py", ["phase", region.toUpperCase()], 10_000);
if (!value || typeof value !== "object" || Array.isArray(value) || "error" in value) {
throw new Error("交易阶段暂不可用");
}
return value;
},
});
Expand Down Expand Up @@ -482,8 +494,40 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
return task;
}

const assetCache = new Map<string, { ino: bigint; mtimeNs: bigint; ctimeNs: bigint; size: bigint; mode: bigint; body: Buffer; etag: string }>();
let watchlistCache: { ino: bigint; mtimeNs: bigint; ctimeNs: bigint; size: bigint; mode: bigint; symbols: string[] } | null = null;
function cachedWatchlist(): string[] {
let st;
try {
accessSync(watchlistFile, constants.R_OK);
st = statSync(watchlistFile, { bigint: true });
} catch (error) {
watchlistCache = null;
if ((error as { code?: string }).code === "ENOENT") return [];
throw new Error("无法读取自选股文件");
}
if (
watchlistCache &&
watchlistCache.ino === st.ino &&
watchlistCache.mtimeNs === st.mtimeNs &&
watchlistCache.ctimeNs === st.ctimeNs &&
watchlistCache.size === st.size &&
watchlistCache.mode === st.mode
) {
return watchlistCache.symbols;
}
try {
const symbols = readWatchlist(watchlistFile);
watchlistCache = { ino: st.ino, mtimeNs: st.mtimeNs, ctimeNs: st.ctimeNs, size: st.size, mode: st.mode, symbols };
return symbols;
} catch (error) {
watchlistCache = null;
throw error;
}
}

function currentSymbols(): string[] {
try { return readWatchlist(watchlistFile); } catch { return []; }
try { return cachedWatchlist(); } catch { return []; }
}

/** Start every due job; resolves when the jobs started by this tick finish. */
Expand All @@ -494,7 +538,16 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
const keep = new Set(list.map(job => job.key));
for (const key of slots.keys()) if (!keep.has(key) && !slots.get(key)!.running) slots.delete(key);
const now = Date.now();
await Promise.all(list.filter(job => due(job, now)).sort((a, b) => a.priority - b.priority).map(start));
const started = limiter.hold(() => {
const tasks = list.filter(job => due(job, now)).sort((a, b) => a.priority - b.priority).map(start);
// Submit queued quote/kline batches before releasing limiter dispatch so priority-1 quotes
// enter workers ahead of priority-2 overseas index jobs.
for (const key of [...pendingBatches.keys()]) {
flushBatch(key.startsWith("quotes:") ? "quotes" : "klines", key);
}
return tasks;
});
await Promise.all(started);
}

async function settle() {
Expand Down Expand Up @@ -548,7 +601,7 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
function snapshot(region: Region) {
lastSeen = Date.now();
viewedRegion = region;
const symbols = readWatchlist(watchlistFile);
const symbols = cachedWatchlist();
kick();
void checkLatest();
return {
Expand Down Expand Up @@ -616,11 +669,12 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
return sendJson(res, 202, { ok: true, pending: limiter.queued });
}
if (rest === "/api/watchlist") {
if (req.method === "GET") return sendJson(res, 200, { symbols: readWatchlist(watchlistFile) });
if (req.method === "GET") return sendJson(res, 200, { symbols: cachedWatchlist() });
if (req.method === "POST") {
const body = await readJson(req);
if (!body?.op) throw new HttpError(400, "必须指定 add 或 remove 操作");
const saved = await updateWatchlist(watchlistFile, body.op, body.symbols);
watchlistCache = null;
kick();
return sendJson(res, 200, { symbols: saved });
}
Expand Down Expand Up @@ -653,19 +707,41 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
const asset = STATIC_FILES.get(rest as "/" | "/app.js" | "/style.css");
if (!asset) return sendJson(res, 404, { error: "Not found" });
const [file, contentType] = asset;
let body: Buffer;
const assetPath = join(webDir, file);
let entry = assetCache.get(file);
try {
body = readFileSync(join(webDir, file));
accessSync(assetPath, constants.R_OK);
const st = statSync(assetPath, { bigint: true });
if (
!entry ||
entry.ino !== st.ino ||
entry.mtimeNs !== st.mtimeNs ||
entry.ctimeNs !== st.ctimeNs ||
entry.size !== st.size ||
entry.mode !== st.mode
) {
const body = readFileSync(assetPath);
const etag = `"${createHash("sha256").update(body).digest("base64url").slice(0, 16)}"`;
entry = { ino: st.ino, mtimeNs: st.mtimeNs, ctimeNs: st.ctimeNs, size: st.size, mode: st.mode, body, etag };
assetCache.set(file, entry);
}
} catch {
assetCache.delete(file);
return sendJson(res, 404, { error: "Not found" });
}
if (req.headers["if-none-match"] === entry.etag) {
res.writeHead(304, { etag: entry.etag, "cache-control": "no-cache" });
res.end();
return;
}
res.writeHead(200, {
"content-type": contentType,
"content-length": body.length,
"content-length": entry.body.length,
etag: entry.etag,
"cache-control": "no-cache",
"x-content-type-options": "nosniff",
});
res.end(req.method === "HEAD" ? undefined : body);
res.end(req.method === "HEAD" ? undefined : entry.body);
} catch (error) {
if (error instanceof HttpError) return sendJson(res, error.status, { error: error.message });
const message = error instanceof Error && !/[/\\]/.test(error.message) ? error.message : "仪表盘服务暂时不可用";
Expand Down
3 changes: 3 additions & 0 deletions dsh/web/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -743,9 +743,12 @@ function renderRows(flash: Map<string, Direction>) {
return;
}
if (!state.snap.watchlist.length) {
for (const key of sparkCache.keys()) if (key.startsWith("watch:")) sparkCache.delete(key);
body.append(emptyRow());
return;
}
const activeWatchKeys = new Set(state.snap.watchlist.map(item => `watch:${item.symbol}`));
for (const key of sparkCache.keys()) if (key.startsWith("watch:") && !activeWatchKeys.has(key)) sparkCache.delete(key);
for (const item of items!) {
const quote = item.quote;
const price = watchPrice(item);
Expand Down
50 changes: 44 additions & 6 deletions tests/test_dsh_dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,14 @@ function fakePython(options: { phase?: string; fail?: (script: string, args: str
? { error: "secret stderr at /private/provider.py" }
: [{ date: "2026-01-01", close: 10, open: 9 }, { date: "2026-01-02", close: 11 }, { date: "2026-01-03", close: "bad" }]));
}
if (script === "trading_calendar.py") return JSON.stringify({ market: args[1], phase: options.phase ?? "post_market", phase_label: "盘后" });
if (script === "trading_calendar.py") {
if (args[0] === "phases") {
return JSON.stringify(Object.fromEntries(
args[1].split(",").map(market => [market, { market, phase: options.phase ?? "post_market", phase_label: "盘后" }]),
));
}
return JSON.stringify({ market: args[1], phase: options.phase ?? "post_market", phase_label: "盘后" });
}
if (args[0] === "quote") return JSON.stringify({ symbol: args[1], name: `Name ${args[1]}`, price: 100, change_pct: 1.2, high: 101, low: 99 });
if (args[0] === "market_indices") return JSON.stringify([{ code: "^HSI", name: "恒生指数", price: 20000, change_pct: -0.5 }]);
if (args[0] === "sector_rankings") return JSON.stringify({ top: [{ name: "元件", change_pct: 5 }], bottom: [{ name: "白酒", change_pct: -3 }] });
Expand Down Expand Up @@ -310,18 +317,22 @@ try {
await handler.tick();
await handler.settle();
assert(py.maxActive() <= 4, `python concurrency ${py.maxActive()} exceeded four`);
assert.equal(py.calls.filter(call => call.startsWith("stock_data.py:quotes ")).length, 1, "one process serves every due quote");
assert(py.calls.some(call => call.startsWith("stock_data.py:quotes ") && call.endsWith(" --watchlist")));
const quoteBatches = py.calls.filter(call => call.startsWith("stock_data.py:quotes "));
assert.equal(quoteBatches.length, 3, "one quote process per active watchlist region (cn, us, hk)");
assert(quoteBatches.every(call => call.endsWith(" --watchlist")));
const cnQuoteBatch = quoteBatches.find(call => call.includes("600519"));
assert(cnQuoteBatch && cnQuoteBatch.includes("sh000001") && !cnQuoteBatch.includes("AAPL"), "CN stock and indices share one batch separate from overseas symbols");
for (const symbol of ["600519", "AAPL", "00700.HK", "sh000001"]) assert.equal(quoted(py.calls, symbol), 1, `missing quote ${symbol}`);
assert.equal(py.timeouts.get(py.calls.find(call => call.startsWith("stock_data.py:quotes "))!), 40_000, "the batch outlives the CLI's own 30 s per-row deadline");
assert(quoteBatches.every(call => py.timeouts.get(call) === 40_000), "the batch outlives the CLI's own 30 s per-row deadline");
for (const expected of [
"stock_data.py:market_indices --region hk",
"stock_data.py:sector_rankings --top 5 --direction both --board-type industry",
"stock_data.py:market_stats --market A",
"stock_data.py:market_stats --market HK",
"stock_data.py:market_stats --market US",
"trading_calendar.py:phase JP",
"trading_calendar.py:phase CN",
]) assert(py.calls.includes(expected), `missing ${expected}`);
assert.equal(py.calls.filter(call => call.startsWith("trading_calendar.py:phase ")).length, 6, "each market phase runs in its own isolated process");
assert(!py.calls.includes("stock_data.py:market_indices --region cn"), "A-share indices use direct quotes");
assert.equal(py.timeouts.get("stock_data.py:market_stats --market US"), 60_000);
const klines = py.calls.filter(call => call.startsWith("stock_data.py:klines "));
Expand Down Expand Up @@ -412,7 +423,7 @@ try {
const failFile = join(temp, "fail", "watchlist.json");
writeWatchlist(failFile, ["AAPL"]);
let failing = false;
const flaky = fakePython({ fail: (_script, args) => failing && args[1] === "AAPL" });
const flaky = fakePython({ fail: (_script, args) => failing && (args[0] === "quote" || args[0] === "kline") && args[1] === "AAPL" });
const failHandler = createDashboardHandler({ runPy: flaky.runPy, watchlistFile: failFile, webDir });
await failHandler.tick();
await failHandler.settle();
Expand Down Expand Up @@ -558,6 +569,12 @@ try {
assert.equal(page.status(), 200);
assert.match(page.body(), /股票仪表盘/);
assert.match(page.headers()["content-type"] as string, /text\/html/);
assert(typeof page.headers().etag === "string", "static assets emit an ETag");
const cachedReq = get("/stock-analysis/");
cachedReq.headers["if-none-match"] = page.headers().etag as string;
const notModified = await call(handler, cachedReq);
assert.equal(notModified.status(), 304, "matching If-None-Match returns 304 without body");
assert.equal(notModified.body(), "");
assert.match(page.body(), /<script src="\.\/app\.js"/, "the page loads the compiled bundle");
assert.match((await call(handler, get("/stock-analysis/app.js"))).headers()["content-type"] as string, /javascript/);
for (const asset of ["app.js", "style.css"]) assert.equal((await call(handler, get(`/stock-analysis/${asset}`))).status(), 200);
Expand Down Expand Up @@ -611,6 +628,27 @@ try {
await resident.settle();
}

// ---------- per-market phase isolation and priority scheduling ----------
{
const phaseFile = join(temp, "phase-isolated", "watchlist.json");
writeWatchlist(phaseFile, ["600519"]);
const py = fakePython({
fail: (script, args) => script === "trading_calendar.py" && args[0] === "phase" && args[1] === "CN",
});
const isolated = createDashboardHandler({ runPy: py.runPy, watchlistFile: phaseFile, webDir });
await isolated.tick();
const snap = (await call(isolated, get("/stock-analysis/api/snapshot"))).json();
assert.equal(snap.phases.cn, null, "failing CN phase stays isolated");
assert.equal(snap.phases.us.phase, "post_market", "unaffected US phase still succeeds independently");
assert.equal(snap.phases.hk.phase, "post_market", "unaffected HK phase still succeeds independently");
assert(py.maxActive() <= 4, "preserves the 4-process worker limit");
// Priority-0 phases (6) and priority-1 CN quotes must all start before priority-2 overseas indices.
const firstQuoteIdx = py.calls.findIndex(c => c.startsWith("stock_data.py:quotes "));
const firstIndexIdx = py.calls.findIndex(c => c.startsWith("stock_data.py:market_indices "));
assert(firstQuoteIdx >= 0 && firstIndexIdx > firstQuoteIdx, `expected quotes (${firstQuoteIdx}) before indices (${firstIndexIdx})`);
isolated.dispose();
}

// ---------- package manifest ----------
const pkg = JSON.parse(readFileSync(join(repoRoot, "dsh", "package.json"), "utf8"));
assert.equal(pkg.exports["./client"], "./dist/client.js");
Expand Down
13 changes: 13 additions & 0 deletions tests/test_market_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,3 +286,16 @@ def fetch(script, args, *a, **kw):
assert "partial_data" in result["data_quality"]["flags"]
assert any("indices" in warning for warning in result["warnings"])
assert any("sectors" in warning for warning in result["warnings"])


def test_review_all_runs_markets_concurrently_in_order(monkeypatch):
import threading

barrier = threading.Barrier(3, timeout=5)

def fake_review(market):
barrier.wait()
return {"market": market}

monkeypatch.setattr(mr, "review_market", fake_review)
assert mr.review_all() == [{"market": "A"}, {"market": "HK"}, {"market": "US"}]
Loading
Loading