Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
127 changes: 111 additions & 16 deletions dsh/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writ
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 @@ -357,10 +357,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 All @@ -382,16 +384,70 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
};
}

const pendingPhases: Array<{ market: string; resolve: (value: unknown) => void; reject: (error: unknown) => void }> = [];
let phasesScheduled = false;
function batchedPhase(region: Region): Promise<unknown> {
const market = region.toUpperCase();
return new Promise((resolve, reject) => {
pendingPhases.push({ market, resolve, reject });
if (!phasesScheduled) {
phasesScheduled = true;
queueMicrotask(flushPhases);
}
});
}
function runSinglePhase(item: { market: string; resolve: (value: unknown) => void; reject: (error: unknown) => void }) {
limiter.run(0, () => py("trading_calendar.py", ["phase", item.market], 10_000)).then(
value => {
if (!value || typeof value !== "object" || Array.isArray(value) || "error" in value) {
item.reject(new Error("交易阶段暂不可用"));
} else {
item.resolve(value);
}
},
error => item.reject(error),
);
}
function flushPhases() {
phasesScheduled = false;
const batch = pendingPhases.splice(0);
if (disposed) {
batch.forEach(item => item.reject(new Error("仪表盘已停止")));
return;
}
if (batch.length === 1) {
runSinglePhase(batch[0]);
return;
}
const markets = batch.map(item => item.market).join(",");
limiter.run(0, () => py("trading_calendar.py", ["phases", markets], 10_000)).then(
Comment thread
Weaxs marked this conversation as resolved.
Resolved
map => {
if (!map || typeof map !== "object" || Array.isArray(map) || "error" in map) {
throw new Error("交易阶段暂不可用");
}
const record = map as Record<string, unknown>;
for (const item of batch) {
const value = record[item.market] as Record<string, unknown> | undefined;
if (!value || typeof value !== "object" || value.error) item.reject(new Error("交易阶段暂不可用"));
else item.resolve(value);
}
},
).catch(error => {
if (disposed) {
batch.forEach(item => item.reject(error));
return;
}
// Process-level failure (timeout/crash): isolate each market with its own phase lookup.
for (const item of batch) runSinglePhase(item);
});
}

function jobs(symbols: string[]): Job[] {
const list: Job[] = [];
for (const region of REGIONS) {
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("交易阶段暂不可用");
return value;
},
key: `phase:${region}`, kind: "phase", region, priority: 0, batched: true,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
run: () => batchedPhase(region),
});
}
for (const symbol of symbols) list.push(quoteJob(symbol, 1));
Expand Down Expand Up @@ -482,8 +538,32 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
return task;
}

const assetCache = new Map<string, { ino: bigint; mtimeNs: bigint; size: bigint; body: Buffer; etag: string }>();
let watchlistCache: { ino: bigint; mtimeNs: bigint; size: bigint; symbols: string[] } | null = null;
function cachedWatchlist(): string[] {
let st;
try {
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.size === st.size) {
return watchlistCache.symbols;
}
try {
const symbols = readWatchlist(watchlistFile);
watchlistCache = { ino: st.ino, mtimeNs: st.mtimeNs, size: st.size, 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 Down Expand Up @@ -548,7 +628,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 +696,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 +734,33 @@ 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));
const st = statSync(assetPath, { bigint: true });
if (!entry || entry.ino !== st.ino || entry.mtimeNs !== st.mtimeNs || entry.size !== st.size) {
const body = readFileSync(assetPath);
const etag = `"${createHash("sha256").update(body).digest("base64url").slice(0, 16)}"`;
entry = { ino: st.ino, mtimeNs: st.mtimeNs, size: st.size, 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
48 changes: 42 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:phases CN,HK,US,JP,KR,TW",
]) assert(py.calls.includes(expected), `missing ${expected}`);
assert.equal(py.calls.filter(call => call.startsWith("trading_calendar.py:")).length, 1, "one process serves every due market phase");
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,25 @@ try {
await resident.settle();
}

// ---------- phase batch failure falls back to isolated per-market phase calls ----------
{
const phaseFile = join(temp, "phase-fallback", "watchlist.json");
writeWatchlist(phaseFile, ["600519"]);
const py = fakePython({
fail: (script, args) =>
script === "trading_calendar.py" && (args[0] === "phases" || (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 via per-market fallback");
assert.equal(snap.phases.hk.phase, "post_market", "unaffected HK phase still succeeds via per-market fallback");
assert(py.calls.some(c => c.startsWith("trading_calendar.py:phases ")), "attempts batched phases first");
assert(py.calls.includes("trading_calendar.py:phase US"), "falls back to isolated phase per market");
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