argo-search 2.16.0 → 2.17.0

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.
Files changed (86) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.es.md +9 -4
  3. package/README.ja.md +9 -4
  4. package/README.ko.md +9 -4
  5. package/README.md +9 -4
  6. package/README.zh.md +9 -4
  7. package/SKILL.md +1 -1
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +3 -3
  10. package/assets/readme/hero.template.svg +121 -0
  11. package/assets/readme/proof-routes.svg +17 -16
  12. package/backends/domain_profiles.json +115 -18
  13. package/backends/engine_registry.yaml +11 -0
  14. package/backends/env_passthrough.txt +2 -0
  15. package/backends/quota_profiles.json +10 -0
  16. package/docs/CHANGELOG.md +17 -1
  17. package/docs/COMMIT_STANDARD.md +10 -0
  18. package/docs/ENGINE_CATALOG.md +32 -30
  19. package/docs/RELEASE_NOTES_v2.17.0.md +64 -0
  20. package/docs/RELEASING.md +1 -1
  21. package/engines/specs/crossref.yaml +2 -0
  22. package/engines/specs/hackernews.yaml +2 -0
  23. package/engines/specs/helve.yaml +49 -0
  24. package/engines/specs/hf_papers.yaml +2 -0
  25. package/engines/specs/openalex.yaml +9 -2
  26. package/package.json +2 -1
  27. package/packages/dsh-plugin/README.md +5 -2
  28. package/packages/dsh-plugin/cordis.patch.yml +4 -1
  29. package/packages/dsh-plugin/dsh/client.js +57 -63
  30. package/packages/dsh-plugin/dsh/diagnostics.js +25 -4
  31. package/packages/dsh-plugin/dsh/index.js +109 -21
  32. package/packages/dsh-plugin/dsh/route-guard.js +95 -0
  33. package/packages/dsh-plugin/dsh/runner.js +49 -6
  34. package/packages/dsh-plugin/dsh/wide-research.js +20 -18
  35. package/packages/dsh-plugin/dsh/workbench-client.js +119 -20
  36. package/packages/dsh-plugin/dsh/workbench-io.js +163 -0
  37. package/packages/dsh-plugin/dsh/workbench-search.js +385 -0
  38. package/packages/dsh-plugin/dsh/workbench-suggestions.js +387 -75
  39. package/packages/dsh-plugin/dsh/workbench.js +234 -497
  40. package/packages/dsh-plugin/package.json +4 -3
  41. package/packages/dsh-plugin/scripts/sync-local.mjs +4 -2
  42. package/packages/dsh-plugin/scripts/sync-local.sh +4 -2
  43. package/packages/dsh-plugin/test/client.test.js +26 -0
  44. package/packages/dsh-plugin/test/diagnostics.test.js +5 -2
  45. package/packages/dsh-plugin/test/index.test.js +150 -1
  46. package/packages/dsh-plugin/test/workbench-concurrency.test.js +98 -0
  47. package/packages/dsh-plugin/test/workbench.test.js +337 -9
  48. package/scripts/adaptive.py +13 -11
  49. package/scripts/browser_auth.py +178 -4
  50. package/scripts/cache.py +68 -69
  51. package/scripts/check_commit_report.py +46 -0
  52. package/scripts/chrome_cdp.py +71 -0
  53. package/scripts/circuit_breaker.py +77 -12
  54. package/scripts/config_cache.py +4 -3
  55. package/scripts/daemon.py +9 -2
  56. package/scripts/engine_add.py +45 -0
  57. package/scripts/engine_dispatch.py +27 -47
  58. package/scripts/engine_failure.py +33 -0
  59. package/scripts/engine_fingerprint.py +114 -0
  60. package/scripts/engine_health.py +130 -0
  61. package/scripts/engine_states.py +50 -0
  62. package/scripts/engines_base.py +7 -16
  63. package/scripts/engines_builders_search.py +19 -8
  64. package/scripts/engines_builders_tech.py +16 -16
  65. package/scripts/engines_fields.py +23 -0
  66. package/scripts/evidence_grounding.py +182 -0
  67. package/scripts/fetch_browser.py +25 -10
  68. package/scripts/gate_manifest_check.py +75 -0
  69. package/scripts/gen_readme_art.py +264 -0
  70. package/scripts/mcp_transport.py +24 -5
  71. package/scripts/numeric_verify.py +9 -0
  72. package/scripts/pre-commit +57 -8
  73. package/scripts/query_operators.py +229 -1
  74. package/scripts/quota.py +19 -37
  75. package/scripts/release.py +16 -1
  76. package/scripts/research_gates.py +85 -1
  77. package/scripts/route_combo.py +13 -1
  78. package/scripts/source_discovery.py +611 -0
  79. package/scripts/sync_backends.py +45 -0
  80. package/sub-skills/ego-search/README.md +9 -0
  81. package/sub-skills/ego-search/scripts/ego_search.py +182 -15
  82. package/sub-skills/ego-search/scripts/pacing.py +291 -0
  83. package/sub-skills/ego-search/scripts/quality.py +262 -6
  84. package/sub-skills/ego-search/scripts/runtime.py +7 -1
  85. package/sub-skills/ego-search/scripts/site_profiles.py +157 -0
  86. package/sub-skills/ego-search/scripts/webbridge_adapter.py +7 -1
@@ -1,52 +1,148 @@
1
1
  /*
2
- * @taxueseek/argo-dsh — 工作台默认推荐引擎(热点 + DSH 语言自适应 + 分模式模板 + 近期检索)
2
+ * @taxueseek/argo-dsh — 工作台推荐引擎(方案二:每日实时热榜 + 零 LLM 兴趣重排 + 个人信号 + 冷启动兜底)
3
+ *
4
+ * 设计原则:
5
+ * 1. 真实信号优先:我的追踪(watches)+ 近期真实检索 + 每日实时热榜;
6
+ * 2. 零 LLM 轻兴趣重排:从历史查询与追踪词抽取实词,将与用户兴趣相关的热点置顶;
7
+ * 3. 每日定时更新一次:仅暴露 refreshTime(HH:MM,默认 08:30),其余全部固定;
8
+ * 4. 静态模板仅作冷启动兜底(真实信号不足 3 条时补位),不抢占正常用户首屏。
3
9
  */
4
10
 
5
- import { readFileSync } from 'node:fs'
6
- import { homedir } from 'node:os'
7
- import { join } from 'node:path'
11
+ import { mkdirSync, readdirSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from 'node:fs'
12
+ import { dirname, join } from 'node:path'
13
+ import { resolveStateDir } from './diagnostics.js'
14
+ import { acquireStateFileLock, releaseStateFileLock } from './workbench-io.js'
8
15
 
9
- const FEED_CACHE_FILE = join(homedir(), '.cache', 'unified-search', 'feed_cache.json')
10
- const QUERY_LOG_FILE = join(homedir(), '.cache', 'unified-search', 'usage_log', 'query.jsonl')
11
- const SUGGESTION_CACHE_TTL_MS = 15 * 60 * 1000
16
+ const RECENT_CACHE_TTL_MS = 30 * 1000
17
+ const RECENT_TAIL_BYTES = 24576
12
18
  const CJK_RE = /[\u4e00-\u9fff]/
19
+ const DEFAULT_REFRESH_TIME = '08:30'
20
+ const TIME_HHMM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/
13
21
 
14
- const MODE_SUGGESTIONS = {
22
+ const HOTSPOT_ENGINES = {
23
+ zh: ['zhihu_hot', 'bilibili_hot'],
24
+ en: ['hackernews', 'x_trending'],
25
+ }
26
+
27
+ // 仅在冷启动(无热榜且无历史/追踪)时兜底,绝不与真实信号抢位
28
+ const COLD_START_FALLBACK = {
15
29
  general: {
16
- zh: ['AI 编程助手最新工程实践', '2026 主流开源模型推理成本对比', 'Mac 本地知识库与全文检索工具推荐'],
17
- en: ['Best open-source local RAG architectures 2026', 'LLM inference latency optimization techniques', 'Agentic coding benchmarks and real-world reviews'],
30
+ zh: ['今日科技与 AI 行业重要进展', '近期值得关注的开源工具发布'],
31
+ en: ['Major AI and engineering updates today', 'Notable open-source releases this week'],
18
32
  },
19
33
  hotspot: {
20
- zh: ['最近一周 AI 行业重大发布与社区争议', '近期大模型价格战与开源生态动态', '本周开发者社区高热技术议题汇总'],
21
- en: ['Top AI engineering discussions this week', 'Recent open-weight model releases and community reaction', 'Major cloud & devtool announcements this week'],
34
+ zh: ['今日全网热议技术与财经事件梳理'],
35
+ en: ['Top trending tech and market discussions today'],
22
36
  },
23
37
  verify: {
24
- zh: ['核验某项行业数据的原始官方报告出处', '核实近期热门开源协议变更公告时间线', '查证某 AI 基准测试成绩的官方复现口径'],
25
- en: ['Verify official benchmark methodology for latest reasoning models', 'Fact-check recent open-source license change announcements', 'Trace primary source for reported developer productivity stats'],
38
+ zh: ['核验近期热点传闻的官方原始出处'],
39
+ en: ['Fact-check trending claims against primary sources'],
26
40
  },
27
41
  research: {
28
- zh: ['端侧模型量化与低延迟推理技术全景调研', '多智能体协作框架的可靠性与评测体系研究', '本地优先软件架构与同步引擎深度对比'],
29
- en: ['Comprehensive survey of local-first sync engines', 'Multi-agent orchestration reliability and evaluation gates', 'On-device LLM quantization trade-offs and benchmarks'],
42
+ zh: ['选择一个主题展开多源深度调研'],
43
+ en: ['Start a multi-source deep research topic'],
30
44
  },
31
45
  compare: {
32
- zh: ['SQLite FTS5 与 Tantivy / Meilisearch 选型对比', '主流终端 AI Agent 工具能力与成本对比', '向量数据库与混合检索方案优缺点对比'],
33
- en: ['SQLite FTS5 vs Tantivy vs Meilisearch comparison', 'Local vector search vs hybrid BM25 trade-offs', 'Self-hosted search engines benchmark comparison'],
46
+ zh: ['对比两个候选技术或产品的优缺点与成本'],
47
+ en: ['Compare two candidate tools on trade-offs and cost'],
34
48
  },
35
49
  academic: {
36
- zh: ['推理时计算扩展(Test-time Compute)最新综述', '检索增强生成(RAG)幻觉抑制与引用溯源论文', '长上下文注意力机制高效实现研究进展'],
37
- en: ['Test-time compute scaling laws recent papers', 'Citation-grounded RAG and faithfulness verification', 'Efficient long-context attention mechanisms survey'],
50
+ zh: ['检索近期代表性论文与基准评测'],
51
+ en: ['Survey recent benchmark papers on your topic'],
38
52
  },
39
53
  plugin: {
40
- zh: ['dsh-zsearch 与 argo-dsh 插件功能对比与评价', '常用代码编辑器 AI 扩展真实口碑与避坑', '浏览器自动化与网页提取插件安全性评估'],
41
- en: ['Compare DSH search plugins capabilities and reliability', 'Top developer productivity extensions security audit', 'Open-source browser automation plugins comparison'],
54
+ zh: ['检索并对比目标插件的功能与社区评价'],
55
+ en: ['Evaluate candidate plugins and community feedback'],
42
56
  },
43
57
  local: {
44
- zh: ['circuit_breaker', 'engine_states', 'workbench'],
45
- en: ['circuit_breaker', 'engine_states', 'wide-research'],
58
+ zh: ['README', 'AGENTS'],
59
+ en: ['README', 'AGENTS'],
46
60
  },
47
61
  }
48
62
 
49
- const feedCache = { ts: 0, zh: [], en: [] }
63
+ const STOP_WORDS = new Set([
64
+ 'the', 'and', 'for', 'with', 'from', 'that', 'this', 'what', 'how', 'why', 'are', 'was',
65
+ '最新', '近期', '今天', '今日', '推荐', '对比', '分析', '如何', '怎么', '什么', '一下',
66
+ ])
67
+
68
+ const recentCache = { ts: 0, dir: '', zh: [], en: [], all: [] }
69
+
70
+ function hotspotStoreFile() {
71
+ return join(resolveStateDir(), 'workbench-hotspots.json')
72
+ }
73
+
74
+ export function normalizeRefreshTime(raw) {
75
+ const s = String(raw || '').trim()
76
+ return TIME_HHMM_RE.test(s) ? s : null
77
+ }
78
+
79
+ export function localDateKey(now = new Date()) {
80
+ const y = now.getFullYear()
81
+ const m = String(now.getMonth() + 1).padStart(2, '0')
82
+ const d = String(now.getDate()).padStart(2, '0')
83
+ return `${y}-${m}-${d}`
84
+ }
85
+
86
+ // 跨进程刷新互斥:多个 DSH 宿主各有 60s 定时器,裸跑会双份抓取 4 引擎并
87
+ // last-write-wins 互踩 workbench-hotspots.json(2026-11-20 审计)。锁实现
88
+ // 统一走 workbench-io.acquireStateFileLock(wx 独占创建,语义对齐
89
+ // scripts/pacing.py 的非阻塞文件锁;2026-11-21 起消灭手抄双实现):
90
+ // 抢不到直接让路——另一宿主当日会刷好并盖章,无需排队等待。
91
+
92
+ export function loadHotspotStore() {
93
+ const empty = {
94
+ refreshTime: DEFAULT_REFRESH_TIME,
95
+ lastRefreshedDate: '',
96
+ lastRefreshedAt: '',
97
+ lastFailedAt: '',
98
+ zh: [],
99
+ en: [],
100
+ }
101
+ try {
102
+ const raw = JSON.parse(readFileSync(hotspotStoreFile(), 'utf8'))
103
+ if (!raw || typeof raw !== 'object') return empty
104
+ return {
105
+ refreshTime: normalizeRefreshTime(raw.refreshTime) || DEFAULT_REFRESH_TIME,
106
+ lastRefreshedDate: typeof raw.lastRefreshedDate === 'string' ? raw.lastRefreshedDate : '',
107
+ lastRefreshedAt: typeof raw.lastRefreshedAt === 'string' ? raw.lastRefreshedAt : '',
108
+ // 全失败退避标记:读侧白名单必须透传,否则触发端永远读不到(2026-11-20 退避方案)
109
+ lastFailedAt: typeof raw.lastFailedAt === 'string' ? raw.lastFailedAt : '',
110
+ zh: Array.isArray(raw.zh) ? raw.zh.filter((x) => typeof x === 'string' && x.trim()) : [],
111
+ en: Array.isArray(raw.en) ? raw.en.filter((x) => typeof x === 'string' && x.trim()) : [],
112
+ }
113
+ } catch {
114
+ return empty
115
+ }
116
+ }
117
+
118
+ export function saveHotspotStore(store) {
119
+ const file = hotspotStoreFile()
120
+ try {
121
+ mkdirSync(dirname(file), { recursive: true })
122
+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}`
123
+ writeFileSync(tmp, JSON.stringify(store, null, 2), 'utf8')
124
+ renameSync(tmp, file)
125
+ } catch { /* ignore */ }
126
+ }
127
+
128
+ export function updateRefreshTime(rawTime) {
129
+ const normalized = normalizeRefreshTime(rawTime)
130
+ if (!normalized) return null
131
+ const store = loadHotspotStore()
132
+ store.refreshTime = normalized
133
+ saveHotspotStore(store)
134
+ return store
135
+ }
136
+
137
+ /** 固定一天更新一次:当天未更新且当前本地时间已达到设定 HH:MM 时到期。 */
138
+ export function isDailyRefreshDue(store, now = new Date()) {
139
+ const today = localDateKey(now)
140
+ if (store?.lastRefreshedDate === today) return false
141
+ const target = normalizeRefreshTime(store?.refreshTime) || DEFAULT_REFRESH_TIME
142
+ const [hh, mm] = target.split(':').map(Number)
143
+ const curMinutes = now.getHours() * 60 + now.getMinutes()
144
+ return curMinutes >= hh * 60 + mm
145
+ }
50
146
 
51
147
  function cleanTitle(raw) {
52
148
  return String(raw || '')
@@ -56,73 +152,240 @@ function cleanTitle(raw) {
56
152
  .slice(0, 44)
57
153
  }
58
154
 
59
- function readFeedHotspots(lang, limit = 4) {
60
- const now = Date.now()
61
- if (now - feedCache.ts < SUGGESTION_CACHE_TTL_MS && (feedCache.zh.length || feedCache.en.length)) {
62
- return (lang === 'en' ? feedCache.en : feedCache.zh).slice(0, limit)
155
+ export async function refreshDailyHotspots({ runCli, now = new Date() } = {}) {
156
+ const store = loadHotspotStore()
157
+ if (typeof runCli !== 'function') return store
158
+ const lock = acquireStateFileLock(`${hotspotStoreFile()}.lock`)
159
+ if (!lock) {
160
+ // 让路要可见:另一宿主正在刷新,调用方(手动 refreshNow)需要据此提示
161
+ // 「另一宿主刷新中」,而不是拿旧时间戳冒充刚刷过(2026-11-21 审计:假成功)
162
+ return { ...store, skipped: 'lock_busy' }
63
163
  }
64
- const zh = []
65
- const en = []
164
+ try {
165
+ return await collectHotspots(store, runCli, now)
166
+ } finally {
167
+ releaseStateFileLock(lock)
168
+ }
169
+ }
170
+
171
+ async function collectHotspots(store, runCli, now) {
172
+ const nextZh = []
173
+ const nextEn = []
174
+ const seen = new Set()
175
+
176
+ const collect = async (lang, engines, bucket) => {
177
+ const query = lang === 'zh' ? '今日热点' : 'trending'
178
+ const settled = await Promise.allSettled(
179
+ engines.map((eng) => runCli(['search', query, '--engine', eng, '-n', '8', '--json', '--fields', 'agent'])),
180
+ )
181
+ for (const res of settled) {
182
+ if (res.status !== 'fulfilled' || !res.value) continue
183
+ const list = Array.isArray(res.value.results) ? res.value.results : []
184
+ for (const item of list) {
185
+ const title = cleanTitle(item?.title)
186
+ if (title.length < 5 || seen.has(title)) continue
187
+ seen.add(title)
188
+ if (bucket.length < 16) bucket.push(title)
189
+ }
190
+ }
191
+ }
192
+
193
+ await Promise.all([
194
+ collect('zh', HOTSPOT_ENGINES.zh, nextZh),
195
+ collect('en', HOTSPOT_ENGINES.en, nextEn),
196
+ ])
197
+
198
+ // 盖章判据:任何语言拿到新数据才算当日已刷。全失败不盖章(当日保持 due,
199
+ // 定时器还会再试),但记 lastFailedAt 供触发端做 1h 退避——否则源长时间挂掉
200
+ // 时会变成每 60s × 4 引擎的重试风暴。
201
+ const updated = {
202
+ refreshTime: store.refreshTime || DEFAULT_REFRESH_TIME,
203
+ zh: nextZh.length > 0 ? nextZh : store.zh,
204
+ en: nextEn.length > 0 ? nextEn : store.en,
205
+ }
206
+ if (nextZh.length + nextEn.length > 0) {
207
+ updated.lastRefreshedDate = localDateKey(now)
208
+ updated.lastRefreshedAt = now.toISOString()
209
+ } else {
210
+ updated.lastRefreshedDate = store.lastRefreshedDate
211
+ updated.lastRefreshedAt = store.lastRefreshedAt
212
+ updated.lastFailedAt = now.toISOString()
213
+ }
214
+ saveHotspotStore(updated)
215
+ return updated
216
+ }
217
+
218
+ /**
219
+ * 触发端工厂:inflight 复用 + 全失败退避,与 refreshDailyHotspots 同住一文件。
220
+ *
221
+ * - inflight 复用:定时刷新进行中手动点「立即刷新」时等待同一次刷新拿真数据,
222
+ * 而不是返回旧 store 让前端误显示「刚刷新过」(2026-11-20 审计:手动刷新假成功)。
223
+ * - 全失败退避:refreshDailyHotspots 全失败时不盖当日章(保持 due 可重试),
224
+ * retryDue 用 lastFailedAt 把重试频率压到 ≥1h 一次,避免源挂掉时 60s × 4 引擎风暴。
225
+ *
226
+ * buildRunner 每次触发时调用,返回当次生效的 runCli(可 async,内部先取 env/凭证)。
227
+ */
228
+ export function createHotspotRefresher({
229
+ buildRunner,
230
+ loadStore = loadHotspotStore,
231
+ failRetryMs = 60 * 60 * 1000,
232
+ } = {}) {
233
+ let inflight = null
234
+ const retryDue = (store) =>
235
+ isDailyRefreshDue(store) &&
236
+ !(store?.lastFailedAt && Number.isFinite(Date.parse(store.lastFailedAt)) &&
237
+ Date.now() - Date.parse(store.lastFailedAt) < failRetryMs)
238
+ const trigger = () => {
239
+ if (inflight) return inflight
240
+ inflight = (async () => {
241
+ try {
242
+ const runCli = typeof buildRunner === 'function' ? await buildRunner() : undefined
243
+ return await refreshDailyHotspots({ runCli })
244
+ } catch { return loadStore() }
245
+ finally { inflight = null }
246
+ })()
247
+ return inflight
248
+ }
249
+ // busy 与 inflight 曾是双变量同置同清(2026-11-21 审计:一个概念两处状态),
250
+ // 收敛为 inflight 单真源派生。
251
+ return { trigger, retryDue, isBusy: () => inflight !== null }
252
+ }
253
+
254
+ function readFileTailSync(filePath, maxBytes) {
255
+ let fd
256
+ try {
257
+ const size = statSync(filePath).size
258
+ if (size <= 0) return ''
259
+ const len = Math.min(size, maxBytes)
260
+ const buf = Buffer.allocUnsafe(len)
261
+ fd = openSync(filePath, 'r')
262
+ const bytesRead = readSync(fd, buf, 0, len, size - len)
263
+ return buf.subarray(0, bytesRead).toString('utf8')
264
+ } finally {
265
+ if (fd !== undefined) {
266
+ try { closeSync(fd) } catch { /* ignore */ }
267
+ }
268
+ }
269
+ }
270
+
271
+ function readLegacyFeedHotspots(lang) {
272
+ const out = []
66
273
  const seen = new Set()
67
274
  try {
68
- const raw = JSON.parse(readFileSync(FEED_CACHE_FILE, 'utf8'))
275
+ const raw = JSON.parse(readFileSync(join(resolveStateDir(), 'feed_cache.json'), 'utf8'))
69
276
  const entries = Object.entries(raw && typeof raw === 'object' ? raw : {})
70
277
  .sort((a, b) => (b[1]?.ts || 0) - (a[1]?.ts || 0))
71
278
  for (const [, feed] of entries) {
72
- const items = Array.isArray(feed?.items) ? feed.items : []
73
- for (const item of items.slice(0, 8)) {
279
+ for (const item of (Array.isArray(feed?.items) ? feed.items : []).slice(0, 6)) {
74
280
  const title = cleanTitle(item?.title)
75
281
  if (title.length < 6 || seen.has(title)) continue
282
+ const isZh = CJK_RE.test(title)
283
+ if ((lang === 'en' && isZh) || (lang === 'zh' && !isZh)) continue
76
284
  seen.add(title)
77
- if (CJK_RE.test(title)) {
78
- if (zh.length < 12) zh.push(title)
79
- } else if (en.length < 12) {
80
- en.push(title)
81
- }
285
+ out.push(title)
286
+ if (out.length >= 8) return out
82
287
  }
83
- if (zh.length >= 12 && en.length >= 12) break
84
288
  }
85
289
  } catch { /* ignore */ }
86
- feedCache.ts = now
87
- feedCache.zh = zh
88
- feedCache.en = en
89
- return (lang === 'en' ? en : zh).slice(0, limit)
290
+ return out
90
291
  }
91
292
 
92
- function readRecentQueries(lang, limit = 3) {
93
- const out = []
293
+ function readRecentQueries(lang, limit = 5) {
294
+ const now = Date.now()
295
+ const dir = resolveStateDir()
296
+ if (recentCache.dir === dir && now - recentCache.ts < RECENT_CACHE_TTL_MS) {
297
+ return {
298
+ list: (lang === 'en' ? recentCache.en : recentCache.zh).slice(0, limit),
299
+ all: recentCache.all,
300
+ }
301
+ }
302
+ const zh = []
303
+ const en = []
304
+ const all = []
94
305
  const seen = new Set()
95
306
  try {
96
- const raw = readFileSync(QUERY_LOG_FILE, 'utf8')
97
- const lines = raw.slice(-24576).split('\n').reverse()
98
- for (const line of lines) {
307
+ const tail = readFileTailSync(join(dir, 'usage_log', 'query.jsonl'), RECENT_TAIL_BYTES)
308
+ for (const line of tail.split('\n').reverse()) {
99
309
  if (!line.trim()) continue
100
310
  try {
101
311
  const row = JSON.parse(line)
102
312
  const q = cleanTitle(row?.query)
103
- if (q.length < 4 || q.length > 40 || (row?.count || 0) <= 0 || seen.has(q)) continue
104
- const isCjk = CJK_RE.test(q)
105
- if ((lang === 'en' && isCjk) || (lang === 'zh' && !isCjk)) continue
313
+ if (q.length < 3 || q.length > 40 || (row?.count || 0) <= 0 || seen.has(q)) continue
106
314
  seen.add(q)
107
- out.push(q)
108
- if (out.length >= limit) break
109
- } catch { /* ignore malformed tail line */ }
315
+ all.push(q)
316
+ if (CJK_RE.test(q)) {
317
+ if (zh.length < 10) zh.push(q)
318
+ } else if (en.length < 10) {
319
+ en.push(q)
320
+ }
321
+ if (zh.length >= 10 && en.length >= 10) break
322
+ } catch { /* ignore */ }
110
323
  }
111
324
  } catch { /* ignore */ }
112
- return out
325
+ Object.assign(recentCache, { ts: now, dir, zh, en, all })
326
+ return { list: (lang === 'en' ? en : zh).slice(0, limit), all }
113
327
  }
114
328
 
115
- export function buildSuggestions(mode = 'general', rawLang = 'zh', shuffle = false) {
116
- const lang = String(rawLang || '').toLowerCase().startsWith('en') ? 'en' : 'zh'
117
- const specPool = MODE_SUGGESTIONS[mode] || MODE_SUGGESTIONS.general
118
- const baseList = [...(specPool[lang] || specPool.zh)]
119
- if (shuffle) baseList.sort(() => Math.random() - 0.5)
329
+ export function extractInterestTokens(queries = [], watches = []) {
330
+ const freq = new Map()
331
+ const addText = (text, weight) => {
332
+ const raw = String(text || '').toLowerCase()
333
+ for (const m of raw.match(/[a-z][a-z0-9_-]{2,}/g) || []) {
334
+ if (!STOP_WORDS.has(m)) freq.set(m, (freq.get(m) || 0) + weight)
335
+ }
336
+ for (const m of raw.match(/[\u4e00-\u9fff]{2,4}/g) || []) {
337
+ if (!STOP_WORDS.has(m)) freq.set(m, (freq.get(m) || 0) + weight)
338
+ }
339
+ }
340
+ for (const w of watches) addText(w?.query || w, 3)
341
+ for (const q of queries) addText(q, 1)
342
+ return [...freq.entries()]
343
+ .sort((a, b) => b[1] - a[1])
344
+ .slice(0, 24)
345
+ .map(([tok]) => tok)
346
+ }
120
347
 
121
- const hotspots = mode === 'local' ? [] : readFeedHotspots(lang, 4)
122
- const recent = mode === 'local' ? [] : readRecentQueries(lang, 3)
348
+ export function rankHotspotsByInterest(hotspots, interestTokens) {
349
+ if (!Array.isArray(hotspots) || hotspots.length === 0) return []
350
+ if (!interestTokens.length) return hotspots.map((q) => ({ query: q, score: 0 }))
351
+ return hotspots
352
+ .map((q, idx) => {
353
+ const low = q.toLowerCase()
354
+ let score = 0
355
+ for (const tok of interestTokens) {
356
+ if (low.includes(tok)) score += 1
357
+ }
358
+ return { query: q, score, idx }
359
+ })
360
+ .sort((a, b) => (b.score - a.score) || (a.idx - b.idx))
361
+ }
362
+
363
+ function readLocalWorkspaceHints(cwd = process.cwd(), limit = 5) {
364
+ try {
365
+ const entries = readdirSync(cwd, { withFileTypes: true })
366
+ .filter((e) => !e.name.startsWith('.') && e.name !== 'node_modules' && e.name !== '__pycache__')
367
+ .map((e) => {
368
+ try {
369
+ return { name: e.name, mtime: statSync(join(cwd, e.name)).mtimeMs }
370
+ } catch {
371
+ return { name: e.name, mtime: 0 }
372
+ }
373
+ })
374
+ .sort((a, b) => b.mtime - a.mtime)
375
+ .slice(0, limit)
376
+ return entries.map((e) => e.name)
377
+ } catch {
378
+ return []
379
+ }
380
+ }
123
381
 
382
+ export function buildSuggestions(mode = 'general', rawLang = 'zh', shuffle = false, options = {}) {
383
+ const lang = String(rawLang || '').toLowerCase().startsWith('en') ? 'en' : 'zh'
384
+ const store = options.hotspotStore || loadHotspotStore()
385
+ const watches = Array.isArray(options.watches) ? options.watches : []
124
386
  const items = []
125
387
  const seen = new Set()
388
+
126
389
  const push = (query, tag, source) => {
127
390
  const q = String(query || '').trim()
128
391
  if (!q || seen.has(q)) return
@@ -130,19 +393,68 @@ export function buildSuggestions(mode = 'general', rawLang = 'zh', shuffle = fal
130
393
  items.push({ query: q, tag, source })
131
394
  }
132
395
 
133
- const hotTag = lang === 'en' ? 'Hot' : '热点'
134
- const modeTag = lang === 'en' ? 'Mode' : '推荐'
135
- const recentTag = lang === 'en' ? 'Recent' : '近期'
396
+ const meta = {
397
+ refreshTime: store.refreshTime || DEFAULT_REFRESH_TIME,
398
+ lastRefreshedAt: store.lastRefreshedAt || '',
399
+ lastRefreshedDate: store.lastRefreshedDate || '',
400
+ }
136
401
 
137
- if (mode === 'hotspot' || mode === 'general' || mode === 'verify') {
138
- for (const q of hotspots.slice(0, 3)) push(q, hotTag, 'feed')
139
- for (const q of baseList) push(q, modeTag, 'template')
140
- for (const q of recent) push(q, recentTag, 'history')
141
- } else {
142
- for (const q of baseList) push(q, modeTag, 'template')
143
- for (const q of hotspots.slice(0, 2)) push(q, hotTag, 'feed')
144
- for (const q of recent.slice(0, 2)) push(q, recentTag, 'history')
402
+ if (mode === 'local') {
403
+ const localTag = lang === 'en' ? 'Workspace' : '工作区'
404
+ const dirs = readLocalWorkspaceHints(options.cwd, 5)
405
+ for (const d of dirs) push(d, localTag, 'workspace')
406
+ if (items.length < 3) {
407
+ const fb = (COLD_START_FALLBACK.local[lang] || COLD_START_FALLBACK.local.zh)
408
+ for (const q of fb) push(q, lang === 'en' ? 'Hint' : '引导', 'fallback')
409
+ }
410
+ return { ok: true, mode, lang, items: items.slice(0, 7), meta }
411
+ }
412
+
413
+ const { list: recentList, all: recentAll } = options.recentQueries
414
+ ? { list: options.recentQueries, all: options.recentQueries }
415
+ : readRecentQueries(lang, 4)
416
+
417
+ const rawHotspots = (lang === 'en' ? store.en : store.zh)
418
+ const hotspotPool = rawHotspots.length > 0 ? [...rawHotspots] : readLegacyFeedHotspots(lang)
419
+ const interestTokens = extractInterestTokens(recentAll, watches)
420
+ const rankedHotspots = rankHotspotsByInterest(hotspotPool, interestTokens)
421
+ if (shuffle && rankedHotspots.length > 2) {
422
+ const head = rankedHotspots.slice(0, 2)
423
+ const rest = rankedHotspots.slice(2).sort(() => Math.random() - 0.5)
424
+ rankedHotspots.splice(0, rankedHotspots.length, ...head, ...rest)
425
+ }
426
+
427
+ const relatedTag = lang === 'en' ? 'For You' : '相关热点'
428
+ const hotTag = lang === 'en' ? 'Hot' : '实时热点'
429
+ const watchTag = lang === 'en' ? 'Watch' : '我的追踪'
430
+ const recentTag = lang === 'en' ? 'Recent' : '近期常搜'
431
+ const fallbackTag = lang === 'en' ? 'Guide' : '引导'
432
+
433
+ // 1. 优先展示与用户兴趣重合的实时热点(最多 3 条)
434
+ for (const h of rankedHotspots.filter((x) => x.score > 0).slice(0, 3)) {
435
+ push(h.query, relatedTag, 'hotspot-matched')
436
+ }
437
+ // 2. 用户正在追踪的 Watch 主题(最多 2 条)
438
+ for (const w of watches.slice(0, 2)) {
439
+ if (w?.query) push(w.query, watchTag, 'watch')
440
+ }
441
+ // 3. 其余实时热点(补足到 4 条热点位)
442
+ for (const h of rankedHotspots.filter((x) => x.score === 0).slice(0, 4)) {
443
+ if (items.length >= 5) break
444
+ push(h.query, hotTag, 'hotspot')
445
+ }
446
+ // 4. 用户近期真实搜索记录
447
+ for (const q of recentList) {
448
+ if (items.length >= 7) break
449
+ push(q, recentTag, 'history')
450
+ }
451
+ // 5. 仅在冷启动(真实信号不足 3 条)时用极简引导补位
452
+ if (items.length < 3) {
453
+ const fbPool = COLD_START_FALLBACK[mode] || COLD_START_FALLBACK.general
454
+ for (const q of fbPool[lang] || fbPool.zh) {
455
+ push(q, fallbackTag, 'fallback')
456
+ }
145
457
  }
146
458
 
147
- return { ok: true, mode, lang, items: items.slice(0, 7) }
459
+ return { ok: true, mode, lang, items: items.slice(0, 7), meta }
148
460
  }