bushido-tradingview-mcp 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -258,6 +258,10 @@ The AI selects the appropriate tools automatically; you do not need to memorize
258
258
 
259
259
  `npm run collect:policy-rates` reads `ECONOMICS:*INTR` for USD/EUR/JPY/GBP/AUD/NZD/CAD/CHF in sequence and appends changes to `~/.tradingview-mcp/policy-rate-first-seen.jsonl`. Every run that successfully acquires all eight currencies, persists values, and restores the chart is also recorded in `~/.tradingview-mcp/policy-rate-collection-heartbeats.jsonl`, whether or not a value changed. This lets the primary test verify first-seen values and collection continuity separately. Override the heartbeat path with `TRADINGVIEW_MCP_POLICY_RATE_COLLECTION_HEARTBEAT_PATH`. Coverage reports distinct run days, same-day reruns, maximum business-day age between runs, intervals beyond the frozen five-day limit, and latest-run age. The script uses the same cross-process chart lock as the MCP server, passes the approved `--confirm-chart-switch`, and verifies restoration after every currency. Because TradingView's 00:00 UTC bar is not a release timestamp, `available_at` is conservatively set to 00:00 UTC on the next business day. This reproducible boundary prevents meeting-day lookahead but is not the actual publication time.
260
260
 
261
+ `npm run health:collections` checks the scheduled-collection heartbeat logs without opening TradingView. Policy-rate collection is stale when it did not complete on the current business day; hourly research collection is stale after two hours. First-seen collection is checked against its latest expected weekday 10:30 or 22:30 JST run, and a completed but partial source run is unhealthy. Missing or malformed evidence fails closed. Use `--scope research`, `--scope policy-rate`, or `--scope first-seen` to read and assess only one collector. The command emits one JSON result, exits nonzero when stale, and stays notification-free by default. On macOS, `--notify` sends a local notification only for stale, partial, or failed checks; it never includes market data.
262
+
263
+ For a repository-location-independent launchd setup, install the package globally (`npm install -g bushido-tradingview-mcp`) and customize the absolute Node and global-module paths in the examples. The [research health agent](docs/launchd/com.tradingview-mcp.collection-health-research.plist.example) runs hourly on all seven days, so a Friday-night outage is detected within the two-hour threshold. The [first-seen health agent](docs/launchd/com.tradingview-mcp.collection-health-first-seen.plist.example) runs 45 minutes after each collection window. The separate [policy-rate health agent](docs/launchd/com.tradingview-mcp.collection-health-policy-rate.plist.example) runs at 11:15 JST on weekdays, after the 10:45 collector. These agents and the first-seen collector do not use `WorkingDirectory`; moving the source repository does not break the installed jobs.
264
+
261
265
  `npm run collect:official-policy-rates` writes to a separate exploration-only official-history store. Sources include the ECB Deposit Facility SDMX CSV; BoC Valet `V39079`; the exclusive date splice of FRED `DFEDTAR` with the midpoint of `DFEDTARL`/`DFEDTARU` from 2008-12-16; RBA F1 `FIRMMCRTD`, joining the official legacy XLS (1990-08-02 through 2010-12-31) to the current daily CSV from 2011-01-04; the SNB policy rate and legacy Libor target-range midpoint; and a frozen BoJ meeting-decision manifest. BoJ periods without a single short-rate target are stored as `value: null` so an obsolete rate is not carried forward. Effective market rates are not substituted for policy targets. Unchanged observations are reduced to change points, while raw snapshots retain original row count and first/last dates to distinguish missing data from unchanged values. Raw bodies retain `raw_sha256`, retrieval time, and Last-Modified vintage and are stored owner-only at `~/.tradingview-mcp/policy-rate-official-raw/<sha256>.raw`; reused hashes are revalidated. This is revised history and must not support prospective/OOS evidence, the primary test, or adoption decisions.
262
266
 
263
267
  `npm run collect:fx-history -- --from 2022-01-01T00:00:00.000Z --to 2026-01-01T00:00:00.000Z` reads `OANDA_FX_HISTORY_ACCOUNT_ID` and `OANDA_FX_HISTORY_ACCESS_TOKEN` only from the environment and retrieves confirmed OANDA v20 `EUR_USD` midpoint M15 candles. Choose `practice` (default) or `live`; credentials and account IDs are never written to stdout, manifests, or raw evidence. Requests are paged at no more than 4,000 bars and timeouts, 429s, and 5xx responses are retried up to three times per page. Successful pages are archived before checkpoints are appended to `~/.tradingview-mcp/fx-history-m15-manifest.jsonl.checkpoints`, so rerunning the same range revalidates archived raw data and resumes from the first incomplete page. Raw responses are stored owner-only by content hash under `~/.tradingview-mcp/fx-history-raw/<sha256>.raw`. The manifest records range, retrieval time, raw and normalized hashes, counts, first/last bars, boundary duplicates, and weekday discontinuities. Equal duplicates are removed; conflicting duplicates stop the run. This revised official history is not a first-seen series and currently supports exploratory long-run CPI/NFP/FOMC research only, not existing OOS adoption gates.
package/build/cdp.js CHANGED
@@ -11,6 +11,46 @@ export class TradingViewNotAvailableError extends Error {
11
11
  this.name = "TradingViewNotAvailableError";
12
12
  }
13
13
  }
14
+ /**
15
+ * `localhost`, `127.0.0.1` and `[::1]` name the same machine, and which of them the
16
+ * endpoint echoes back is not ours to decide — Chrome answers with whatever Host it was
17
+ * asked on. Treating them as interchangeable keeps a working setup working; it does not
18
+ * widen the check, because all three stay on this host.
19
+ */
20
+ const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
21
+ const defaultPort = (protocol) => protocol === "wss:" || protocol === "https:" ? "443" : "80";
22
+ /**
23
+ * The `/json` response is whatever answered the CDP port, so `webSocketDebuggerUrl` is
24
+ * untrusted input. `findChartTarget` validates the *page* URL, but the socket opened next
25
+ * is a separate address that nothing checked: an endpoint that squats the port can pass
26
+ * the page check with a genuine-looking tradingview.com/chart URL and still point the
27
+ * debugger session at a host of its choosing, carrying everything sent over it — Pine
28
+ * source, alert payloads — off this machine. That defeats the operational rule of opening
29
+ * the debug port only while the server is in use, since a closed port is exactly what
30
+ * another process is free to take.
31
+ */
32
+ export function assertDebuggerWebSocketUrl(candidate, baseUrl) {
33
+ let socket;
34
+ try {
35
+ socket = new URL(candidate);
36
+ }
37
+ catch {
38
+ throw new TradingViewNotAvailableError("the chart target did not supply a usable webSocketDebuggerUrl");
39
+ }
40
+ if (socket.protocol !== "ws:" && socket.protocol !== "wss:") {
41
+ throw new TradingViewNotAvailableError("the chart target's webSocketDebuggerUrl is not a WebSocket URL");
42
+ }
43
+ // The candidate is never echoed: it is attacker-shaped by assumption and may carry a
44
+ // query string of its own.
45
+ const endpoint = new URL(baseUrl);
46
+ const sameHost = socket.hostname === endpoint.hostname ||
47
+ (LOOPBACK_HOSTNAMES.has(socket.hostname) && LOOPBACK_HOSTNAMES.has(endpoint.hostname));
48
+ const samePort = (socket.port || defaultPort(socket.protocol)) === (endpoint.port || defaultPort(endpoint.protocol));
49
+ if (!sameHost || !samePort) {
50
+ throw new TradingViewNotAvailableError("the chart target's webSocketDebuggerUrl points somewhere other than the CDP endpoint itself");
51
+ }
52
+ return socket.href;
53
+ }
14
54
  /**
15
55
  * Minimal CDP client bound to the TradingView chart page.
16
56
  * Connects lazily and reconnects automatically if the app restarts.
@@ -97,12 +137,29 @@ export class CdpClient {
97
137
  */
98
138
  async connect() {
99
139
  const target = await this.findChartTarget();
100
- const ws = new WebSocket(target.webSocketDebuggerUrl, {
140
+ const socketUrl = assertDebuggerWebSocketUrl(target.webSocketDebuggerUrl, this.baseUrl);
141
+ const ws = new WebSocket(socketUrl, {
101
142
  maxPayload: 256 * 1024 * 1024,
102
143
  });
103
144
  const pending = new Map();
104
145
  ws.on("message", (data) => {
105
- const msg = JSON.parse(data.toString());
146
+ // This handler is synchronous, so a throw here is an unhandled listener exception
147
+ // and the process exits — there is no uncaughtException handler. A frame that is
148
+ // not JSON is not a reply to anything we sent, so drop it and let the request it
149
+ // would have answered fail on its own timeout.
150
+ let msg;
151
+ try {
152
+ const parsed = JSON.parse(data.toString());
153
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
154
+ throw new Error("frame is not a CDP message object");
155
+ }
156
+ msg = parsed;
157
+ }
158
+ catch (err) {
159
+ console.error(`[tradingview-mcp] ignoring unparsable CDP frame: ` +
160
+ redactSecrets(err instanceof Error ? err.message : String(err)));
161
+ return;
162
+ }
106
163
  if (msg.id !== undefined && pending.has(msg.id)) {
107
164
  pending.get(msg.id).resolve(msg);
108
165
  pending.delete(msg.id);
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  import { CotClient } from "./cot.js";
2
3
  import { CmeDailyBulletinClient } from "./cmeDailyBulletin.js";
3
4
  import { pathToFileURL } from "node:url";
@@ -8,6 +9,7 @@ import { TreasuryRealYieldClient } from "./realYield.js";
8
9
  import { RealYieldFirstSeenStore, resolveRealYieldHistoryPath } from "./realYieldHistory.js";
9
10
  import { PolicyRateFirstSeenStore, resolvePolicyRateHistoryPath } from "./policyRateHistory.js";
10
11
  import { PolicyRateCollectionHeartbeatStore, resolvePolicyRateCollectionHeartbeatPath } from "./policyRateCollectionHeartbeat.js";
12
+ import { FirstSeenCollectionHeartbeatStore, resolveFirstSeenCollectionHeartbeatPath } from "./firstSeenCollectionHeartbeat.js";
11
13
  const DEFAULT_COT_SYMBOLS = ["OANDA:EURUSD", "OANDA:XAUUSD"];
12
14
  const MAX_COT_COLLECTION_WEEKS = 52;
13
15
  export function parseCollectionCliArguments(argv, env = process.env) {
@@ -51,19 +53,31 @@ async function main() {
51
53
  const futuresOiStore = new FuturesOpenInterestFirstSeenStore(resolveFuturesOpenInterestHistoryPath());
52
54
  const policyRateStore = new PolicyRateFirstSeenStore(resolvePolicyRateHistoryPath());
53
55
  const policyRateHeartbeats = new PolicyRateCollectionHeartbeatStore(resolvePolicyRateCollectionHeartbeatPath());
56
+ const firstSeenHeartbeats = new FirstSeenCollectionHeartbeatStore(resolveFirstSeenCollectionHeartbeatPath());
54
57
  const coverage = () => getUnifiedFirstSeenCoverage({ cot: cotStore, realYield: realYieldStore, futuresOpenInterest: futuresOiStore, policyRates: policyRateStore, policyRateHeartbeats });
55
- const result = args.command === "coverage"
56
- ? await coverage()
57
- : await collectFirstSeenSources({
58
- cot: new CotClient(undefined, undefined, cotStore),
59
- realYield: new TreasuryRealYieldClient(undefined, undefined, realYieldStore),
60
- cmeGoldOpenInterest: new CmeDailyBulletinClient(),
61
- futuresOpenInterest: futuresOiStore,
62
- cotSymbols: args.cotSymbols,
63
- cotWeeks: args.cotWeeks,
64
- coverage,
65
- });
66
- process.stdout.write(`${JSON.stringify(result)}\n`);
58
+ if (args.command === "coverage") {
59
+ process.stdout.write(`${JSON.stringify({ ...(await coverage()), first_seen_collection_heartbeat: await firstSeenHeartbeats.coverage() })}\n`);
60
+ return;
61
+ }
62
+ const result = await collectFirstSeenSources({
63
+ cot: new CotClient(undefined, undefined, cotStore),
64
+ realYield: new TreasuryRealYieldClient(undefined, undefined, realYieldStore),
65
+ cmeGoldOpenInterest: new CmeDailyBulletinClient(),
66
+ futuresOpenInterest: futuresOiStore,
67
+ cotSymbols: args.cotSymbols,
68
+ cotWeeks: args.cotWeeks,
69
+ coverage,
70
+ });
71
+ const heartbeat = await firstSeenHeartbeats.recordRun({
72
+ observed_at: result.observed_at,
73
+ status: result.status,
74
+ cot_symbols: args.cotSymbols,
75
+ cot_complete: result.cot.filter((item) => item.status === "complete").length,
76
+ real_yield_status: result.real_yield.status,
77
+ cme_gold_open_interest_status: result.cme_gold_open_interest.status,
78
+ coverage_status: result.coverage.status,
79
+ });
80
+ process.stdout.write(`${JSON.stringify({ ...result, heartbeat: { sequence: heartbeat.sequence, recorded_at: heartbeat.first_seen_at } })}\n`);
67
81
  if (result.status === "partial")
68
82
  process.exitCode = 1;
69
83
  }
@@ -0,0 +1,81 @@
1
+ import { isCanonicalTimestamp } from "./firstSeenStore.js";
2
+ function assertThreshold(value, integer) {
3
+ if (!Number.isFinite(value) || value < 0 || (integer && !Number.isInteger(value))) {
4
+ throw new Error("collection health threshold must be a non-negative number");
5
+ }
6
+ }
7
+ function assertCoverageAge(age, latest) {
8
+ if (age === null) {
9
+ if (latest !== null)
10
+ throw new Error("collection health age is missing for a recorded heartbeat");
11
+ return;
12
+ }
13
+ if (!Number.isFinite(age) || age < 0)
14
+ throw new Error("collection health age must be a non-negative number");
15
+ if (latest === null || !isCanonicalTimestamp(latest))
16
+ throw new Error("collection health latest heartbeat must be canonical");
17
+ }
18
+ export function evaluateCollectionHealth(input) {
19
+ const scope = input.scope ?? "all";
20
+ if (!isCanonicalTimestamp(input.checkedAt))
21
+ throw new Error("collection health checked_at must be canonical");
22
+ assertThreshold(input.maxPolicyRateAgeBusinessDays, true);
23
+ assertThreshold(input.maxResearchAgeHours, false);
24
+ const checkPolicyRate = scope === "all" || scope === "policy-rate";
25
+ const checkResearch = scope === "all" || scope === "research";
26
+ const checkFirstSeen = scope === "all" || scope === "first-seen";
27
+ if (checkPolicyRate)
28
+ assertCoverageAge(input.policyRate.latest_run_age_business_days, input.policyRate.latest_collected_at);
29
+ if (checkResearch)
30
+ assertCoverageAge(input.research.latest_run_age_hours, input.research.latest_collected_at);
31
+ if (checkFirstSeen) {
32
+ if (!isCanonicalTimestamp(input.firstSeen.latest_expected_run_at))
33
+ throw new Error("first-seen expected run must be canonical");
34
+ if (input.firstSeen.latest_collected_at !== null && !isCanonicalTimestamp(input.firstSeen.latest_collected_at))
35
+ throw new Error("first-seen latest heartbeat must be canonical");
36
+ }
37
+ const issues = [];
38
+ const policyAge = input.policyRate.latest_run_age_business_days;
39
+ if (checkPolicyRate && policyAge === null) {
40
+ issues.push({ code: "policy_rate_collection_missing", collector: "policy_rate", age: null, threshold: input.maxPolicyRateAgeBusinessDays, unit: "business_days" });
41
+ }
42
+ else if (checkPolicyRate && policyAge !== null && policyAge > input.maxPolicyRateAgeBusinessDays) {
43
+ issues.push({ code: "policy_rate_collection_stale", collector: "policy_rate", age: policyAge, threshold: input.maxPolicyRateAgeBusinessDays, unit: "business_days" });
44
+ }
45
+ const researchAge = input.research.latest_run_age_hours;
46
+ if (checkResearch && researchAge === null) {
47
+ issues.push({ code: "research_collection_missing", collector: "research", age: null, threshold: input.maxResearchAgeHours, unit: "hours" });
48
+ }
49
+ else if (checkResearch && researchAge !== null && researchAge > input.maxResearchAgeHours) {
50
+ issues.push({ code: "research_collection_stale", collector: "research", age: researchAge, threshold: input.maxResearchAgeHours, unit: "hours" });
51
+ }
52
+ if (checkFirstSeen && input.firstSeen.latest_collected_at === null) {
53
+ issues.push({ code: "first_seen_collection_missing", collector: "first_seen", age: null, threshold: 0, unit: "scheduled_runs" });
54
+ }
55
+ else if (checkFirstSeen && !input.firstSeen.latest_run_meets_schedule) {
56
+ issues.push({ code: "first_seen_collection_stale", collector: "first_seen", age: 1, threshold: 0, unit: "scheduled_runs" });
57
+ }
58
+ if (checkFirstSeen && input.firstSeen.latest_run_status === "partial") {
59
+ issues.push({ code: "first_seen_collection_partial", collector: "first_seen", age: 1, threshold: 0, unit: "scheduled_runs" });
60
+ }
61
+ return {
62
+ checked_at: input.checkedAt,
63
+ scope,
64
+ status: issues.length === 0 ? "healthy" : "stale",
65
+ should_notify: issues.length > 0,
66
+ thresholds: {
67
+ max_policy_rate_age_business_days: input.maxPolicyRateAgeBusinessDays,
68
+ max_research_age_hours: input.maxResearchAgeHours,
69
+ },
70
+ policy_rate: checkPolicyRate ? input.policyRate : null,
71
+ research: checkResearch ? input.research : null,
72
+ first_seen: checkFirstSeen ? input.firstSeen : null,
73
+ issues,
74
+ };
75
+ }
76
+ export function collectionHealthNotification(result) {
77
+ if (!result.should_notify)
78
+ return "";
79
+ const names = result.issues.map((issue) => issue.collector === "policy_rate" ? "policy-rate" : issue.collector === "first_seen" ? "first-seen" : "research");
80
+ return `Collection heartbeat unhealthy: ${[...new Set(names)].join(", ")}. Inspect collector and scheduler logs; CDP-dependent collectors also require TradingView debugging.`;
81
+ }
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { pathToFileURL } from "node:url";
4
+ import { collectionHealthNotification, evaluateCollectionHealth } from "./collectionHealth.js";
5
+ import { PolicyRateCollectionHeartbeatStore, resolvePolicyRateCollectionHeartbeatPath } from "./policyRateCollectionHeartbeat.js";
6
+ import { ResearchCollectionHeartbeatStore, resolveResearchCollectionHeartbeatPath } from "./researchCollectionHeartbeat.js";
7
+ import { FirstSeenCollectionHeartbeatStore, resolveFirstSeenCollectionHeartbeatPath } from "./firstSeenCollectionHeartbeat.js";
8
+ const DEFAULT_MAX_POLICY_RATE_AGE_BUSINESS_DAYS = 0;
9
+ const DEFAULT_MAX_RESEARCH_AGE_HOURS = 2;
10
+ function numericArgument(argv, index, name) {
11
+ const raw = argv[index + 1];
12
+ if (raw === undefined)
13
+ throw new Error(`${name} requires a value`);
14
+ const value = Number(raw);
15
+ if (!Number.isFinite(value) || value < 0)
16
+ throw new Error(`${name} must be a non-negative number`);
17
+ return value;
18
+ }
19
+ export function parseCollectionHealthCliArguments(argv) {
20
+ let scope = "all";
21
+ let maxPolicyRateAgeBusinessDays = DEFAULT_MAX_POLICY_RATE_AGE_BUSINESS_DAYS;
22
+ let maxResearchAgeHours = DEFAULT_MAX_RESEARCH_AGE_HOURS;
23
+ let notify = false;
24
+ for (let index = 0; index < argv.length; index += 1) {
25
+ const argument = argv[index];
26
+ if (argument === "--notify")
27
+ notify = true;
28
+ else if (argument === "--scope") {
29
+ const value = argv[index + 1];
30
+ if (value !== "all" && value !== "policy-rate" && value !== "first-seen" && value !== "research") {
31
+ throw new Error("--scope must be all, policy-rate, first-seen, or research");
32
+ }
33
+ scope = value;
34
+ index += 1;
35
+ }
36
+ else if (argument === "--max-policy-rate-age-business-days") {
37
+ maxPolicyRateAgeBusinessDays = numericArgument(argv, index, argument);
38
+ if (!Number.isInteger(maxPolicyRateAgeBusinessDays))
39
+ throw new Error(`${argument} must be an integer`);
40
+ index += 1;
41
+ }
42
+ else if (argument === "--max-research-age-hours") {
43
+ maxResearchAgeHours = numericArgument(argv, index, argument);
44
+ index += 1;
45
+ }
46
+ else {
47
+ throw new Error(`unknown argument: ${argument}`);
48
+ }
49
+ }
50
+ return { scope, maxPolicyRateAgeBusinessDays, maxResearchAgeHours, notify };
51
+ }
52
+ export async function sendMacNotification(message) {
53
+ if (process.platform !== "darwin")
54
+ throw new Error("--notify is supported only on macOS");
55
+ await new Promise((resolve, reject) => {
56
+ const child = spawn("/usr/bin/osascript", [
57
+ "-e", "on run argv",
58
+ "-e", "display notification (item 1 of argv) with title \"TradingView-MCP\"",
59
+ "-e", "end run",
60
+ message,
61
+ ], { stdio: "ignore" });
62
+ child.once("error", reject);
63
+ child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`osascript exited with status ${code ?? "unknown"}`)));
64
+ });
65
+ }
66
+ export async function checkCollectionHealth(args, now = new Date()) {
67
+ const emptyPolicyRate = { latest_collected_at: null, latest_run_age_business_days: null };
68
+ const emptyResearch = { latest_collected_at: null, latest_run_age_hours: null };
69
+ const emptyFirstSeen = { latest_collected_at: null, latest_run_status: null, latest_expected_run_at: now.toISOString(), latest_run_meets_schedule: false };
70
+ const policyRate = args.scope === "policy-rate" || args.scope === "all"
71
+ ? await new PolicyRateCollectionHeartbeatStore(resolvePolicyRateCollectionHeartbeatPath()).coverage(now)
72
+ : emptyPolicyRate;
73
+ const research = args.scope === "research" || args.scope === "all"
74
+ ? await new ResearchCollectionHeartbeatStore(resolveResearchCollectionHeartbeatPath()).coverage(now)
75
+ : emptyResearch;
76
+ const firstSeen = args.scope === "first-seen" || args.scope === "all"
77
+ ? await new FirstSeenCollectionHeartbeatStore(resolveFirstSeenCollectionHeartbeatPath()).coverage(now)
78
+ : emptyFirstSeen;
79
+ return evaluateCollectionHealth({
80
+ scope: args.scope,
81
+ checkedAt: now.toISOString(),
82
+ maxPolicyRateAgeBusinessDays: args.maxPolicyRateAgeBusinessDays,
83
+ maxResearchAgeHours: args.maxResearchAgeHours,
84
+ policyRate: {
85
+ latest_collected_at: policyRate.latest_collected_at,
86
+ latest_run_age_business_days: policyRate.latest_run_age_business_days,
87
+ },
88
+ research: {
89
+ latest_collected_at: research.latest_collected_at,
90
+ latest_run_age_hours: research.latest_run_age_hours,
91
+ },
92
+ firstSeen: {
93
+ latest_collected_at: firstSeen.latest_collected_at,
94
+ latest_run_status: firstSeen.latest_run_status,
95
+ latest_expected_run_at: firstSeen.latest_expected_run_at,
96
+ latest_run_meets_schedule: firstSeen.latest_run_meets_schedule,
97
+ },
98
+ });
99
+ }
100
+ export async function runCollectionHealthCli(argv, dependencies = {}) {
101
+ const deps = {
102
+ checkHealth: checkCollectionHealth,
103
+ notify: sendMacNotification,
104
+ notificationsSupported: process.platform === "darwin",
105
+ writeOutput: (message) => process.stdout.write(message),
106
+ writeError: (message) => process.stderr.write(message),
107
+ ...dependencies,
108
+ };
109
+ try {
110
+ const args = parseCollectionHealthCliArguments(argv);
111
+ const result = await deps.checkHealth(args);
112
+ deps.writeOutput(`${JSON.stringify(result)}\n`);
113
+ if (result.should_notify && args.notify && deps.notificationsSupported)
114
+ await deps.notify(collectionHealthNotification(result));
115
+ return result.status === "stale" ? 1 : 0;
116
+ }
117
+ catch (error) {
118
+ deps.writeError(`collection health check failed: ${error instanceof Error ? error.message : String(error)}\n`);
119
+ if (argv.includes("--notify") && deps.notificationsSupported) {
120
+ try {
121
+ await deps.notify("Collection health check failed. Inspect collection-health stderr log.");
122
+ }
123
+ catch { /* stderr already records the failure */ }
124
+ }
125
+ return 1;
126
+ }
127
+ }
128
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
129
+ process.exitCode = await runCollectionHealthCli(process.argv.slice(2));
130
+ }
@@ -0,0 +1,103 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { AppendOnlyFirstSeenLog, isCalendarDate, isCanonicalTimestamp } from "./firstSeenStore.js";
4
+ const MAX_HISTORY_BYTES = 16 * 1024 * 1024;
5
+ const MAX_RECORD_BYTES = 2_048;
6
+ const JST_OFFSET_MS = 9 * 60 * 60 * 1_000;
7
+ const RUN_SLOTS = [{ hour: 22, minute: 30 }, { hour: 10, minute: 30 }];
8
+ export const resolveFirstSeenCollectionHeartbeatPath = (configuredPath = process.env.TRADINGVIEW_MCP_FIRST_SEEN_COLLECTION_HEARTBEAT_PATH) => configuredPath?.trim() || join(homedir(), ".tradingview-mcp", "first-seen-collection-heartbeats.jsonl");
9
+ export function latestExpectedFirstSeenRunAt(now) {
10
+ if (!Number.isFinite(now.getTime()))
11
+ throw new Error("as_of must be a valid timestamp");
12
+ const jst = new Date(now.getTime() + JST_OFFSET_MS);
13
+ for (let daysBack = 0; daysBack < 8; daysBack += 1) {
14
+ const day = new Date(Date.UTC(jst.getUTCFullYear(), jst.getUTCMonth(), jst.getUTCDate() - daysBack));
15
+ const weekday = day.getUTCDay();
16
+ if (weekday === 0 || weekday === 6)
17
+ continue;
18
+ for (const slot of RUN_SLOTS) {
19
+ const expected = new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), slot.hour - 9, slot.minute));
20
+ if (expected.getTime() <= now.getTime())
21
+ return expected.toISOString();
22
+ }
23
+ }
24
+ throw new Error("could not resolve the latest first-seen collection schedule");
25
+ }
26
+ const validateRecord = (value, line) => {
27
+ const suffix = line === undefined ? "" : ` at line ${line}`;
28
+ if (!value || typeof value !== "object" || Array.isArray(value))
29
+ throw new Error(`invalid first-seen collection heartbeat${suffix}`);
30
+ const record = value;
31
+ if (record.schema_version !== "1.0" || record.series !== "first_seen_collection_heartbeat")
32
+ throw new Error(`unsupported first-seen collection heartbeat schema${suffix}`);
33
+ if (!Number.isSafeInteger(record.sequence) || (record.sequence ?? 0) < 1)
34
+ throw new Error(`invalid first-seen collection heartbeat sequence${suffix}`);
35
+ if (typeof record.observation_date !== "string" || !isCalendarDate(record.observation_date))
36
+ throw new Error(`invalid first-seen collection heartbeat observation_date${suffix}`);
37
+ if (typeof record.first_seen_at !== "string" || !isCanonicalTimestamp(record.first_seen_at))
38
+ throw new Error(`invalid first-seen collection heartbeat first_seen_at${suffix}`);
39
+ if (record.observation_date !== record.first_seen_at.slice(0, 10))
40
+ throw new Error(`first-seen collection heartbeat observation_date must equal first_seen date${suffix}`);
41
+ if (record.status !== "complete" && record.status !== "partial")
42
+ throw new Error(`invalid first-seen collection heartbeat status${suffix}`);
43
+ if (!Array.isArray(record.cot_symbols) || record.cot_symbols.length < 1 || record.cot_symbols.some((symbol) => typeof symbol !== "string" || symbol.length < 1))
44
+ throw new Error(`first-seen collection heartbeat must name every COT symbol${suffix}`);
45
+ if (new Set(record.cot_symbols).size !== record.cot_symbols.length)
46
+ throw new Error(`duplicate first-seen collection heartbeat COT symbol${suffix}`);
47
+ if (!Number.isInteger(record.cot_complete) || (record.cot_complete ?? -1) < 0 || (record.cot_complete ?? 0) > record.cot_symbols.length)
48
+ throw new Error(`invalid first-seen collection heartbeat COT count${suffix}`);
49
+ if (record.real_yield_status !== "complete" && record.real_yield_status !== "error")
50
+ throw new Error(`invalid first-seen collection heartbeat real-yield status${suffix}`);
51
+ if (record.cme_gold_open_interest_status !== "complete" && record.cme_gold_open_interest_status !== "error")
52
+ throw new Error(`invalid first-seen collection heartbeat CME status${suffix}`);
53
+ if (record.coverage_status !== "complete" && record.coverage_status !== "partial")
54
+ throw new Error(`invalid first-seen collection heartbeat coverage status${suffix}`);
55
+ const expectedStatus = record.cot_complete === record.cot_symbols.length && record.real_yield_status === "complete" && record.cme_gold_open_interest_status === "complete" && record.coverage_status === "complete" ? "complete" : "partial";
56
+ if (record.status !== expectedStatus)
57
+ throw new Error(`first-seen collection heartbeat status does not match source outcomes${suffix}`);
58
+ return record;
59
+ };
60
+ export class FirstSeenCollectionHeartbeatStore {
61
+ log;
62
+ constructor(filePath) {
63
+ this.log = new AppendOnlyFirstSeenLog(filePath, "first-seen collection heartbeat", validateRecord, { maxFileBytes: MAX_HISTORY_BYTES, maxRecordBytes: MAX_RECORD_BYTES });
64
+ }
65
+ async recordRun(input) {
66
+ if (!isCanonicalTimestamp(input.observed_at))
67
+ throw new Error("first-seen collection heartbeat observed_at must be a canonical timestamp");
68
+ return this.log.serialize(async () => {
69
+ const records = await this.log.readAllUnlocked();
70
+ const record = validateRecord({
71
+ schema_version: "1.0",
72
+ sequence: records.length + 1,
73
+ series: "first_seen_collection_heartbeat",
74
+ observation_date: input.observed_at.slice(0, 10),
75
+ first_seen_at: input.observed_at,
76
+ status: input.status,
77
+ cot_symbols: input.cot_symbols,
78
+ cot_complete: input.cot_complete,
79
+ real_yield_status: input.real_yield_status,
80
+ cme_gold_open_interest_status: input.cme_gold_open_interest_status,
81
+ coverage_status: input.coverage_status,
82
+ });
83
+ await this.log.appendUnlocked(record);
84
+ return record;
85
+ });
86
+ }
87
+ async coverage(asOf = new Date()) {
88
+ const expected = latestExpectedFirstSeenRunAt(asOf);
89
+ return this.log.serialize(async () => {
90
+ const records = await this.log.readAllUnlocked();
91
+ const latest = records.at(-1);
92
+ return {
93
+ records: records.length,
94
+ earliest_collected_at: records[0]?.first_seen_at ?? null,
95
+ latest_collected_at: latest?.first_seen_at ?? null,
96
+ latest_run_status: latest?.status ?? null,
97
+ partial_runs: records.filter((record) => record.status === "partial").length,
98
+ latest_expected_run_at: expected,
99
+ latest_run_meets_schedule: latest !== undefined && latest.first_seen_at >= expected,
100
+ };
101
+ });
102
+ }
103
+ }
@@ -1,9 +1,10 @@
1
1
  import { constants } from "node:fs";
2
2
  import { lstat, mkdir, open, unlink } from "node:fs/promises";
3
3
  import { randomUUID } from "node:crypto";
4
- import { dirname } from "node:path";
4
+ import { dirname, resolve } from "node:path";
5
5
  import { assertNotSymbolicLink, syncDirectoryEntry, noFollowFlag, openExclusiveFile, posixModeEnforced } from "./fsDurability.js";
6
6
  const LOCK_WAIT_MS = 2_000;
7
+ const pathQueues = new Map();
7
8
  export const isCalendarDate = (value) => {
8
9
  const match = value.match(/^(\d{4})-(\d{2})-(\d{2})$/);
9
10
  if (!match)
@@ -28,7 +29,13 @@ export class AppendOnlyFirstSeenLog {
28
29
  label;
29
30
  validateRecord;
30
31
  limits;
31
- queue = Promise.resolve();
32
+ /**
33
+ * The queue is keyed on the file, not on the spelling of the path that reached this
34
+ * constructor. Two logs given `a/x.jsonl` and `a/./x.jsonl` write through the same lock
35
+ * and must share one queue; keying on the raw string would hand them separate queues and
36
+ * silently restore the race the queue exists to prevent.
37
+ */
38
+ queueKey;
32
39
  constructor(filePath, label, validateRecord, limits) {
33
40
  this.filePath = filePath;
34
41
  this.label = label;
@@ -36,6 +43,7 @@ export class AppendOnlyFirstSeenLog {
36
43
  this.limits = limits;
37
44
  if (!filePath)
38
45
  throw new Error(`${label} history path is required`);
46
+ this.queueKey = resolve(filePath);
39
47
  }
40
48
  async ensureDirectory() {
41
49
  const directory = dirname(this.filePath);
@@ -200,7 +208,8 @@ export class AppendOnlyFirstSeenLog {
200
208
  }
201
209
  }
202
210
  serialize(operation) {
203
- const result = this.queue.then(async () => {
211
+ const predecessor = pathQueues.get(this.queueKey) ?? Promise.resolve();
212
+ const result = predecessor.then(async () => {
204
213
  const release = await this.acquireFileLock();
205
214
  try {
206
215
  return await operation();
@@ -209,7 +218,12 @@ export class AppendOnlyFirstSeenLog {
209
218
  await release();
210
219
  }
211
220
  });
212
- this.queue = result.then(() => undefined, () => undefined);
221
+ const settled = result.then(() => undefined, () => undefined);
222
+ pathQueues.set(this.queueKey, settled);
223
+ void settled.then(() => {
224
+ if (pathQueues.get(this.queueKey) === settled)
225
+ pathQueues.delete(this.queueKey);
226
+ });
213
227
  return result;
214
228
  }
215
229
  }
package/build/redact.js CHANGED
@@ -3,10 +3,27 @@
3
3
  * local logs: URL userinfo (user:pass@host), URL query strings (which may
4
4
  * carry session ids) and bearer/token values. Surrounding text is kept so
5
5
  * error messages stay actionable.
6
+ *
7
+ * The scheme runs are bounded rather than open-ended. An unbounded
8
+ * `[\w+.-]*` before `://` costs one scan of the whole remaining string at
9
+ * every letter that turns out not to start a scheme, which is quadratic: a
10
+ * 40 KB message took 2.9 s and an 80 KB one 11.7 s. This function runs on
11
+ * every tool error and on every page exception, both of which can carry
12
+ * text the page chose, so a long enough message froze the single Node
13
+ * thread. `{0,64}` caps the per-position cost; no real scheme comes close.
6
14
  */
15
+ /**
16
+ * Nothing useful is lost by capping the result: this is diagnostic text, not
17
+ * data. Truncation happens after redaction, so a secret can never survive by
18
+ * straddling the cut.
19
+ */
20
+ export const MAX_REDACTED_CHARS = 4096;
7
21
  export function redactSecrets(text) {
8
- return text
9
- .replace(/([a-z][\w+.-]*:\/\/)[^\s/@]+@/gi, "$1***@")
10
- .replace(/([a-z][\w+.-]*:\/\/[^\s?"'<>()[\]]+)\?[^\s"'<>()[\]]*/gi, "$1?***")
22
+ const redacted = text
23
+ .replace(/([a-z][\w+.-]{0,64}:\/\/)[^\s/@]+@/gi, "$1***@")
24
+ .replace(/([a-z][\w+.-]{0,64}:\/\/[^\s?"'<>()[\]]+)\?[^\s"'<>()[\]]*/gi, "$1?***")
11
25
  .replace(/\b(bearer|token|api[_-]?key|authorization)([=:]\s*|\s+)[\w.~+/-]+=*/gi, "$1$2***");
26
+ return redacted.length <= MAX_REDACTED_CHARS
27
+ ? redacted
28
+ : `${redacted.slice(0, MAX_REDACTED_CHARS)}… [truncated]`;
12
29
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bushido-tradingview-mcp",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "MCP server that lets AI analyze the TradingView desktop app via Chrome DevTools Protocol",
5
5
  "keywords": [
6
6
  "mcp",
@@ -13,7 +13,9 @@
13
13
  "author": "tedorigawa001",
14
14
  "type": "module",
15
15
  "bin": {
16
- "tradingview-mcp": "build/index.js"
16
+ "tradingview-mcp": "build/index.js",
17
+ "tradingview-mcp-health": "build/collectionHealthCli.js",
18
+ "tradingview-mcp-collect-first-seen": "build/collectionCli.js"
17
19
  },
18
20
  "main": "build/index.js",
19
21
  "files": [
@@ -41,6 +43,7 @@
41
43
  "walk-forward": "node build/walkForwardCli.js",
42
44
  "collect:first-seen": "node build/collectionCli.js collect",
43
45
  "coverage:first-seen": "node build/collectionCli.js coverage",
46
+ "health:collections": "node build/collectionHealthCli.js",
44
47
  "collect:policy-rates": "node build/policyRateCollectionCli.js --confirm-chart-switch",
45
48
  "collect:official-policy-rates": "node build/officialPolicyRateCollectionCli.js --confirm-exploratory-import",
46
49
  "collect:fx-history": "node build/fxHistoryCollectionCli.js --confirm-external-fetch",