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,17 +1,14 @@
1
1
  import test from 'node:test'
2
2
  import assert from 'node:assert/strict'
3
3
  import { EventEmitter } from 'node:events'
4
- import { createWorkbenchHandler } from '../dsh/workbench.js'
4
+ import { Readable } from 'node:stream'
5
+ import { buildSearchCliArgs, createWorkbenchHandler } from '../dsh/workbench.js'
5
6
 
6
7
  function mockReq(method, url, bodyObj = null) {
7
- const req = new EventEmitter()
8
+ const req = bodyObj !== null ? Readable.from([Buffer.from(JSON.stringify(bodyObj))]) : new EventEmitter()
8
9
  req.method = method
9
10
  req.url = url
10
11
  req.headers = { host: '127.0.0.1:8080' }
11
- queueMicrotask(() => {
12
- if (bodyObj !== null) req.emit('data', Buffer.from(JSON.stringify(bodyObj)))
13
- req.emit('end')
14
- })
15
12
  return req
16
13
  }
17
14
 
@@ -22,7 +19,18 @@ function mockRes() {
22
19
  statusCode: 200,
23
20
  writableEnded: false,
24
21
  destroyed: false,
25
- setHeader(k, v) { headers[k.toLowerCase()] = v },
22
+ headersSent: false,
23
+ // 保真 Node 语义:flushHeaders 后再 setHeader 抛 ERR_HTTP_HEADERS_SENT
24
+ flushHeaders() { this.headersSent = true },
25
+ setHeader(k, v) {
26
+ if (this.headersSent) throw new Error('ERR_HTTP_HEADERS_SENT')
27
+ headers[k.toLowerCase()] = v
28
+ },
29
+ writeHead(code, hdrs = {}) {
30
+ this.statusCode = code
31
+ for (const [k, v] of Object.entries(hdrs)) headers[k.toLowerCase()] = v
32
+ },
33
+ write(data = '') { chunks += String(data); return true },
26
34
  end(data = '') {
27
35
  chunks += String(data)
28
36
  this.writableEnded = true
@@ -38,7 +46,7 @@ test('workbench /argo/api/health exposes local mode, egoSearch and breaker summa
38
46
  try {
39
47
  const res = mockRes()
40
48
  await handler(mockReq('GET', '/argo/api/health'), res)
41
- assert.equal(res.statusCode, 200)
49
+ assert.equal(res.statusCode, 200, res.text())
42
50
  const data = res.json()
43
51
  assert.equal(data.ok, true)
44
52
  assert.ok(Array.isArray(data.modes))
@@ -85,8 +93,328 @@ test('workbench /argo/api/suggestions adapts to mode and DSH locale', async () =
85
93
  const en = resEn.json()
86
94
  assert.equal(en.ok, true)
87
95
  assert.equal(en.lang, 'en')
88
- assert.ok(en.items.some(it => it.tag === 'Mode'))
96
+ assert.ok(en.items.length > 0)
97
+ const enTags = new Set(['For You', 'Hot', 'Watch', 'Recent', 'Guide'])
98
+ assert.ok(en.items.every(it => enTags.has(it.tag)))
99
+ } finally {
100
+ handler.dispose()
101
+ }
102
+ })
103
+
104
+ test('workbench uses host default model without overriding maxTokens and surfaces real LLM failure', async () => {
105
+ let capturedOpts
106
+ const mockCtx = {
107
+ get(name) {
108
+ if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'commandcode', model: 'deepseek/deepseek-v4.1-flash' }) }
109
+ if (name === 'llm') {
110
+ return {
111
+ async *stream(opts) {
112
+ capturedOpts = opts
113
+ yield { type: 'finish', reason: { kind: 'error', failure: { message: 'finish_reason=length' } } }
114
+ },
115
+ }
116
+ }
117
+ return undefined
118
+ },
119
+ }
120
+ const handler = createWorkbenchHandler(mockCtx, {}, () => ({}))
121
+ try {
122
+ const res = mockRes()
123
+ await handler(mockReq('POST', '/argo/api/followup', {
124
+ query: 'test',
125
+ mode: 'general',
126
+ question: 'why?',
127
+ cards: [{ index: 1, title: 'T', url: 'https://example.com', domain: 'example.com', snippet: 'S' }],
128
+ }), res)
129
+ assert.equal(res.statusCode, 200, res.text())
130
+ assert.equal(capturedOpts.provider, 'commandcode')
131
+ assert.equal(capturedOpts.model, 'deepseek/deepseek-v4.1-flash')
132
+ assert.equal(capturedOpts.maxTokens, undefined)
133
+ assert.equal(capturedOpts.reasoningEffort, undefined)
134
+ assert.ok(res.text().includes('commandcode/deepseek/deepseek-v4.1-flash'))
135
+ assert.ok(res.text().includes('finish_reason=length'))
136
+ assert.ok(!res.text().includes('未配置默认模型'))
137
+ } finally {
138
+ handler.dispose()
139
+ }
140
+ })
141
+
142
+ test('workbench followup tolerates null cards/history entries without hanging the SSE response', async () => {
143
+ // 2026-11-18 实跑复现:cards:[null] 在 flushHeaders 后于 buildEvidenceContext
144
+ // 抛 TypeError → catch 落 sendJson → setHeader 二次抛 ERR_HTTP_HEADERS_SENT
145
+ // → 响应永久悬挂。修复=入口元素过滤 + sendJson 判 headersSent 改发 SSE failure。
146
+ let capturedMessages
147
+ const mockCtx = {
148
+ get(name) {
149
+ if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'p', model: 'm' }) }
150
+ if (name === 'llm') {
151
+ return {
152
+ async *stream(opts) {
153
+ capturedMessages = opts.messages
154
+ yield { type: 'finish', reason: { kind: 'stop' } }
155
+ },
156
+ }
157
+ }
158
+ return undefined
159
+ },
160
+ }
161
+ const handler = createWorkbenchHandler(mockCtx, {}, () => ({}))
162
+ try {
163
+ const res = mockRes()
164
+ await handler(mockReq('POST', '/argo/api/followup', {
165
+ query: 'test',
166
+ mode: 'general',
167
+ question: 'why?',
168
+ cards: [null, 'garbage', { index: 1, title: 'T', url: 'https://example.com', domain: 'example.com', snippet: 'S' }],
169
+ history: [null, { role: 'user', text: 'previous turn' }],
170
+ }), res)
171
+ assert.equal(res.statusCode, 200)
172
+ assert.equal(res.writableEnded, true, '响应必须干净收尾,不得悬挂')
173
+ assert.ok(res.text().includes('event: done'), `应以 done 事件收尾,实际: ${res.text().slice(-160)}`)
174
+ // 合法 history 条目应过滤后到达模型(null 条目被剔除、合法条目保留)
175
+ const flattened = JSON.stringify(capturedMessages)
176
+ assert.ok(flattened.includes('previous turn'), '合法 history 条目应到达模型')
177
+ assert.ok(!flattened.includes('null'), 'null 条目不得混入 messages')
89
178
  } finally {
90
179
  handler.dispose()
91
180
  }
92
181
  })
182
+
183
+ test('workbench CLI args keep every flag before `--` so dash-leading queries stay literal', () => {
184
+ const args = buildSearchCliArgs('--list-engines', 'general', true, { verify: 2 })
185
+ const sep = args.indexOf('--')
186
+ assert.ok(sep > 0, `必须存在 -- 分隔,实际 ${JSON.stringify(args)}`)
187
+ assert.equal(args[sep + 1], '--list-engines', 'query 必须紧跟 -- 之后')
188
+ assert.equal(args[args.length - 1], '--list-engines')
189
+ assert.ok(args.slice(0, sep).includes('--json'), 'flag 必须全部前置到 -- 之前')
190
+ assert.ok(args.slice(0, sep).includes('--no-cache'), 'refresh 的 --no-cache 也须前置')
191
+ assert.ok(!args.slice(0, sep).includes('--list-engines'), 'query 不得混入 flag 区')
192
+ })
193
+
194
+ test('workbench research gate passes when stats are supplied alongside valid citations', async () => {
195
+ const { evaluateGates } = await import('../dsh/wide-research.js')
196
+ const gate = evaluateGates({
197
+ answer: '核心结论基于多源证据 [1][2][3]。',
198
+ sources: [
199
+ { url: 'https://a.example.com/1', title: 'A', domain: 'a.example.com' },
200
+ { url: 'https://b.example.com/2', title: 'B', domain: 'b.example.com' },
201
+ { url: 'https://c.example.com/3', title: 'C', domain: 'c.example.com' },
202
+ ],
203
+ tracks: [{ id: 't1', title: 'T1' }],
204
+ warnings: [],
205
+ stats: { sourceCount: 3, completedTracks: 1, failedTracks: 0 },
206
+ })
207
+ assert.equal(gate.passed, true)
208
+ })
209
+
210
+ test('index apply re-registers envResolver after dispose (HMR safe) and sets rc.5 provider metadata', async () => {
211
+ const { apply } = await import('../dsh/index.js')
212
+ const { resolveEnv } = await import('../dsh/runner.js')
213
+ const cleanups = []
214
+ const registered = []
215
+ const mkCtx = () => ({
216
+ effect: (fn) => { const off = fn(); if (typeof off === 'function') cleanups.push(off) },
217
+ tools: { register: () => () => {}, guard: () => () => {} },
218
+ subagents: {},
219
+ systemPrompt: { section: () => () => {} },
220
+ web: {
221
+ registerSearchProvider: (p) => { registered.push(p); return () => {} },
222
+ registerFetchProvider: (p) => { registered.push(p); return () => {} },
223
+ search: async () => ({ sources: [] }),
224
+ searchReady: async () => true,
225
+ },
226
+ get: () => undefined,
227
+ })
228
+ apply(mkCtx(), { nativeTools: [] })
229
+ while (cleanups.length) cleanups.pop()()
230
+ // 二次 apply 模拟同进程 HMR 重载
231
+ apply(mkCtx(), { nativeTools: [], argoEnv: ['ARGO_NO_CACHE=1'] })
232
+ const env = await resolveEnv({}, { argoEnv: ['ARGO_NO_CACHE=1'], keyRefs: [] })
233
+ assert.equal(env?.ARGO_NO_CACHE, '1')
234
+ const searchProv = registered.find(p => p.id === 'argo' && typeof p.search === 'function')
235
+ assert.ok(searchProv?.title)
236
+ assert.ok(searchProv?.description)
237
+ assert.equal(typeof searchProv?.ready, 'function')
238
+ while (cleanups.length) cleanups.pop()()
239
+ })
240
+
241
+ test('workbench /argo/api/* enforces TCP peer loopback fence against spoofed headers', async () => {
242
+ const handler = createWorkbenchHandler({}, {}, () => ({}))
243
+ try {
244
+ // 局域网对端即使伪造 Host: 127.0.0.1 + X-Forwarded-For: 127.0.0.1 且不带 Origin 也必须被拒
245
+ const lanReq = mockReq('GET', '/argo/api/health')
246
+ lanReq.socket = { remoteAddress: '192.168.1.50' }
247
+ lanReq.headers = { host: '127.0.0.1:8080', 'x-forwarded-for': '127.0.0.1' }
248
+ const lanRes = mockRes()
249
+ await handler(lanReq, lanRes)
250
+ assert.equal(lanRes.statusCode, 403)
251
+ assert.equal(lanRes.json().error, 'forbidden_origin')
252
+
253
+ // 本机 IPv4-mapped 回环放行,但跨站 Origin 仍被拦(防 DNS rebinding)
254
+ const okReq = mockReq('GET', '/argo/api/health')
255
+ okReq.socket = { remoteAddress: '::ffff:127.0.0.1' }
256
+ const okRes = mockRes()
257
+ await handler(okReq, okRes)
258
+ assert.equal(okRes.statusCode, 200)
259
+
260
+ const badOriginReq = mockReq('GET', '/argo/api/health')
261
+ badOriginReq.socket = { remoteAddress: '127.0.0.1' }
262
+ badOriginReq.headers = { host: '127.0.0.1:8080', origin: 'https://evil.example' }
263
+ const badOriginRes = mockRes()
264
+ await handler(badOriginReq, badOriginRes)
265
+ assert.equal(badOriginRes.statusCode, 403)
266
+ } finally {
267
+ handler.dispose()
268
+ }
269
+ })
270
+
271
+ test('workbench /argo/api/auth-status triggers background live verification once', async () => {
272
+ const verifyCalls = []
273
+ const handler = createWorkbenchHandler({}, {}, () => ({}), {
274
+ runAuthCli: async (cliArgs) => {
275
+ if (cliArgs[1] === 'status') return { profiles: [{ site: 'x.com', created: '2026-11-20' }] }
276
+ if (cliArgs[1] === 'verify') {
277
+ verifyCalls.push(cliArgs[2])
278
+ return { ok: true, site: cliArgs[2], state: 'ready' }
279
+ }
280
+ return {}
281
+ },
282
+ })
283
+ try {
284
+ const rAuth1 = mockRes()
285
+ await handler(mockReq('GET', '/argo/api/auth-status'), rAuth1)
286
+ assert.equal(rAuth1.statusCode, 200)
287
+ assert.equal(rAuth1.json().profiles[0].site, 'x.com')
288
+ await new Promise((r) => setTimeout(r, 10))
289
+ assert.deepEqual(verifyCalls, ['x.com'], '冷启动未核验站点应在后台静默触发一次活体复核')
290
+
291
+ const rAuth2 = mockRes()
292
+ await handler(mockReq('GET', '/argo/api/auth-status'), rAuth2)
293
+ assert.equal(rAuth2.json().profiles[0].verification.state, 'ready')
294
+ } finally {
295
+ handler.dispose()
296
+ }
297
+ })
298
+
299
+ test('workbench suggestions rank daily hotspots by user interest and enforce once-daily schedule', async () => {
300
+ const { buildSuggestions, isDailyRefreshDue } = await import('../dsh/workbench-suggestions.js')
301
+ const store = {
302
+ refreshTime: '09:00',
303
+ lastRefreshedDate: '2026-11-19',
304
+ lastRefreshedAt: '2026-11-19T01:00:00.000Z',
305
+ zh: ['某明星新剧官宣定档', 'DeepSeek 新一代推理模型架构解析', '今日全国天气降温预警'],
306
+ en: [],
307
+ }
308
+ const out = buildSuggestions('general', 'zh', false, {
309
+ hotspotStore: store,
310
+ watches: [{ query: 'DeepSeek 推理模型进展' }],
311
+ recentQueries: ['DeepSeek 成本对比'],
312
+ })
313
+ assert.equal(out.items[0].query, 'DeepSeek 新一代推理模型架构解析', '命中用户兴趣词的热点应置顶')
314
+ assert.equal(out.items[0].source, 'hotspot-matched')
315
+ assert.equal(out.items.some((x) => x.source === 'fallback'), false, '有真实信号时静态兜底模板不得抢位')
316
+
317
+ // 一天更新一次判据:未到点 false、到点且未刷 true、当天已刷 false
318
+ assert.equal(isDailyRefreshDue(store, new Date('2026-11-20T08:59:00')), false)
319
+ assert.equal(isDailyRefreshDue(store, new Date('2026-11-20T09:00:00')), true)
320
+ assert.equal(isDailyRefreshDue({ ...store, lastRefreshedDate: '2026-11-20' }, new Date('2026-11-20T18:00:00')), false)
321
+
322
+ // /argo/api/suggestions/config 校验非法时间并返回更新后的每日时间
323
+ const handler = createWorkbenchHandler({}, {}, () => ({}))
324
+ try {
325
+ const rBad = mockRes()
326
+ await handler(mockReq('POST', '/argo/api/suggestions/config', { refreshTime: '25:99' }), rBad)
327
+ assert.equal(rBad.statusCode, 400)
328
+ const rOk = mockRes()
329
+ await handler(mockReq('POST', '/argo/api/suggestions/config', { refreshTime: '09:00' }), rOk)
330
+ assert.equal(rOk.statusCode, 200)
331
+ assert.equal(rOk.json().refreshTime, '09:00')
332
+ } finally {
333
+ handler.dispose()
334
+ }
335
+ })
336
+
337
+ test('refreshDailyHotspots: 全失败不盖当日章并记 lastFailedAt,拿到新数据才盖章', async () => {
338
+ const { mkdtempSync } = await import('node:fs')
339
+ const { tmpdir } = await import('node:os')
340
+ const { join } = await import('node:path')
341
+ const prevState = process.env.ARGO_STATE_DIR
342
+ process.env.ARGO_STATE_DIR = mkdtempSync(join(tmpdir(), 'argo-wb-hotspot-'))
343
+ try {
344
+ const { refreshDailyHotspots } = await import('../dsh/workbench-suggestions.js')
345
+ const now = new Date('2026-11-20T09:00:00')
346
+ const emptyCli = async () => ({ results: [] })
347
+
348
+ // 全失败:保留旧章(当日仍 due,定时器可重试),写 lastFailedAt 供 1h 退避
349
+ const failed = await refreshDailyHotspots({
350
+ runCli: emptyCli, now,
351
+ })
352
+ assert.equal(failed.lastRefreshedDate, '', '全失败不得盖当日章')
353
+ assert.ok(failed.lastFailedAt, '全失败须记 lastFailedAt')
354
+ assert.equal(failed.lastRefreshedAt, '')
355
+
356
+ // 成功:盖当日章,清除 lastFailedAt
357
+ const okCli = async () => ({ results: [{ title: '今日全新热搜条目测试样例' }] })
358
+ const ok = await refreshDailyHotspots({ runCli: okCli, now })
359
+ assert.equal(ok.lastRefreshedDate, '2026-11-20')
360
+ assert.ok(ok.lastRefreshedAt)
361
+ assert.equal(ok.lastFailedAt, undefined, '成功后不得残留失败标记')
362
+ assert.equal(ok.zh.length, 1)
363
+ } finally {
364
+ process.env.ARGO_STATE_DIR = prevState
365
+ }
366
+ })
367
+
368
+ test('refreshDailyHotspots: 跨进程锁让路——他进程持锁时不重复抓取', async () => {
369
+ const { closeSync, mkdtempSync, openSync, unlinkSync } = await import('node:fs')
370
+ const { tmpdir } = await import('node:os')
371
+ const { join } = await import('node:path')
372
+ const prevState = process.env.ARGO_STATE_DIR
373
+ const stateDir = mkdtempSync(join(tmpdir(), 'argo-wb-lock-'))
374
+ process.env.ARGO_STATE_DIR = stateDir
375
+ try {
376
+ const { refreshDailyHotspots } = await import('../dsh/workbench-suggestions.js')
377
+ // 模拟另一宿主持锁:先造锁文件,再触发刷新
378
+ const lockPath = join(stateDir, 'workbench-hotspots.json.lock')
379
+ const lockFd = openSync(lockPath, 'wx')
380
+ try {
381
+ let cliCalls = 0
382
+ const out = await refreshDailyHotspots({
383
+ runCli: async () => { cliCalls += 1; return { results: [{ title: '不该被抓取的条目样例' }] } },
384
+ now: new Date('2026-11-21T09:00:00'),
385
+ })
386
+ assert.equal(cliCalls, 0, '持锁期间他进程不得发起 CLI 抓取')
387
+ assert.equal(out.zh.length, 0, '让路时返回现有 store')
388
+ } finally {
389
+ closeSync(lockFd)
390
+ unlinkSync(lockPath)
391
+ }
392
+ // 锁释放后正常抓取
393
+ const out2 = await refreshDailyHotspots({
394
+ runCli: async () => ({ results: [{ title: '锁释放后的真实热搜条目' }] }),
395
+ now: new Date('2026-11-21T09:01:00'),
396
+ })
397
+ assert.equal(out2.zh.length, 1)
398
+ } finally {
399
+ process.env.ARGO_STATE_DIR = prevState
400
+ }
401
+ })
402
+
403
+ test('resolveArgoBin: ARGO_BIN 显式覆盖 > monorepo > install venv > PATH 裸名', async () => {
404
+ const { existsSync } = await import('node:fs')
405
+ const { homedir } = await import('node:os')
406
+ const { dirname, join } = await import('node:path')
407
+ const { fileURLToPath } = await import('node:url')
408
+ const { resolveArgoBin } = await import('../dsh/workbench-io.js')
409
+ // 显式覆盖最优先(用户指路,零猜测)
410
+ assert.equal(resolveArgoBin({ ARGO_BIN: '/custom/argo' }), '/custom/argo')
411
+ // 无覆盖时按候选链取第一个存在的:monorepo > install.sh 默认 venv > 裸名走 PATH
412
+ const here = join(dirname(dirname(fileURLToPath(import.meta.url))), 'dsh')
413
+ const chain = [
414
+ join(here, '..', '..', '..', 'bin', 'argo'),
415
+ join(homedir(), '.local', 'share', 'argo', '.venv', 'bin', 'argo'),
416
+ 'argo',
417
+ ]
418
+ const expected = chain.find((p, i) => i === chain.length - 1 || existsSync(p))
419
+ assert.equal(resolveArgoBin({}), expected)
420
+ })
@@ -176,19 +176,22 @@ class AdaptiveLearner:
176
176
 
177
177
  @contextlib.contextmanager
178
178
  def batch(self):
179
- """合并多次 record 为单次 SQLite commit,保持 record 调用面不变。"""
180
- with self._lock:
181
- self._batch_depth = getattr(self, "_batch_depth", 0) + 1
179
+ """合并多次 record 为单次 SQLite commit,保持 record 调用面不变。
180
+
181
+ batch 状态跟随线程局部连接(self._local),避免线程 A 开启 batch 期间
182
+ 线程 B 的独立连接跳过 commit 导致写事务悬空锁库。
183
+ """
184
+ self._local.batch_depth = getattr(self._local, "batch_depth", 0) + 1
182
185
  try:
183
186
  yield
184
187
  finally:
185
- with self._lock:
186
- self._batch_depth = max(0, getattr(self, "_batch_depth", 1) - 1)
187
- if self._batch_depth == 0 and getattr(self, "_batch_dirty", False):
188
+ self._local.batch_depth = max(0, getattr(self._local, "batch_depth", 1) - 1)
189
+ if self._local.batch_depth == 0 and getattr(self._local, "batch_dirty", False):
190
+ with self._lock:
188
191
  conn = self._connect()
189
192
  self._prune_foreign(conn)
190
193
  conn.commit()
191
- self._batch_dirty = False
194
+ self._local.batch_dirty = False
192
195
 
193
196
  def _connect(self) -> sqlite3.Connection:
194
197
  """线程本地复用连接,避免 route 每次 open/close SQLite。"""
@@ -276,8 +279,8 @@ class AdaptiveLearner:
276
279
  (engine, 1 if success else 0, latency_ms, cost, time.time(),
277
280
  1 if empty else 0, q, dom, lg),
278
281
  )
279
- if getattr(self, "_batch_depth", 0) > 0:
280
- self._batch_dirty = True
282
+ if getattr(self._local, "batch_depth", 0) > 0:
283
+ self._local.batch_dirty = True
281
284
  else:
282
285
  conn.commit()
283
286
  # 清掉该引擎的全部缓存键(含场景分桶键),见 get_score 的缓存口径
@@ -393,8 +396,7 @@ class AdaptiveLearner:
393
396
  score, samples = self._blend_bucket(
394
397
  score, samples,
395
398
  self._bucket_row(engine, domain or "", lang or ""), purpose)
396
-
397
- self._score_cache[key] = (score, samples, now + self.SCORE_CACHE_TTL)
399
+ self._score_cache[key] = (score, samples, now + self.SCORE_CACHE_TTL)
398
400
  return score, samples
399
401
 
400
402
  # 场景桶向全局分收缩的先验强度:桶内有效观测 n 条时桶的权重为 n/(n+2)。
@@ -105,6 +105,7 @@ def _read_meta(d: Path) -> dict:
105
105
 
106
106
  def _write_meta(d: Path, host: str, created: str | None = None) -> None:
107
107
  """原子写 meta.json:profile 的 argo 登记标记(Chrome 不认识也不在乎它)。"""
108
+ import argo_paths
108
109
  prev = _read_meta(d)
109
110
  meta = {
110
111
  "site": host,
@@ -112,9 +113,7 @@ def _write_meta(d: Path, host: str, created: str | None = None) -> None:
112
113
  "last_used": time.strftime("%Y-%m-%dT%H:%M:%S"),
113
114
  "argo": "browser-profiles/v1",
114
115
  }
115
- tmp = d / f"meta.json.tmp.{os.getpid()}"
116
- tmp.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
117
- os.replace(tmp, d / "meta.json")
116
+ argo_paths.atomic_write_json(d / "meta.json", meta)
118
117
 
119
118
 
120
119
  def profile_for(url_or_host: str) -> str | None:
@@ -174,6 +173,7 @@ def login(url_or_host: str, chrome_path: str | None = None,
174
173
  msg += "(该 profile 可能已有 Chrome 在跑:关掉它或先 argo auth logout)"
175
174
  return {"ok": False, "site": host, "error": msg[:200]}
176
175
 
176
+ saved = False
177
177
  try:
178
178
  if confirm is None:
179
179
  print(f"\n[{host}] 已在打开的 Chrome 窗口中登录/扫码。", file=sys.stderr)
@@ -186,12 +186,15 @@ def login(url_or_host: str, chrome_path: str | None = None,
186
186
  else:
187
187
  confirm()
188
188
  _write_meta(d, host)
189
+ saved = True
189
190
  return {"ok": True, "site": host, "profile": str(d)}
190
191
  finally:
191
192
  try:
192
193
  proc.stop()
193
194
  except Exception:
194
195
  pass
196
+ if fresh and not saved:
197
+ shutil.rmtree(d, ignore_errors=True)
195
198
 
196
199
 
197
200
  def status() -> list[dict]:
@@ -246,6 +249,162 @@ def touch(url_or_host: str) -> None:
246
249
  pass
247
250
 
248
251
 
252
+ # ─── 四态防抖判别、活体会话校验与评论上下文封顶 ─────────────────────────────
253
+
254
+ _SEC_VERIFY_URL_RE = re.compile(r"captcha|security[._-]?verif|challenge|/account/access", re.I)
255
+ _SEC_VERIFY_TEXT_RE = re.compile(
256
+ r"安全验证|安全限制|IP存在风险|访问受限|异常访问|操作频繁|请完成验证|verify you are human",
257
+ re.I,
258
+ )
259
+ _SIGNED_OUT_URL_RE = re.compile(r"website-login|/i/flow/login|/login(?:/|\?|$)|/signin(?:/|\?|$)", re.I)
260
+ _LOGIN_WALL_TEXT_RE = re.compile(
261
+ r"登录后推荐更懂你的笔记|登录后查看|请先登录|立即登录以继续|log in to continue|sign in to view",
262
+ re.I,
263
+ )
264
+
265
+
266
+ def detect_page_auth_state(
267
+ url: str,
268
+ title: str = "",
269
+ body_text: str = "",
270
+ *,
271
+ has_security_modal: bool = False,
272
+ has_login_modal: bool = False,
273
+ after_search: bool = False,
274
+ ) -> str:
275
+ """四态(+搜索受限)判别纯函数:全部返回 engine_states.PAGE_AUTH_* 常量。"""
276
+ import engine_states as _es
277
+
278
+ # 入口统一收敛 str:调用方可能传非 str(测试桩的 MagicMock 等),
279
+ # regex 收到非 str 会 TypeError 顺异常链拖垮整条 fetch
280
+ # (tests/test_fetch_auth_lane.py::test_browser_fetch_marks_login_provenance 回归)。
281
+ href = str(url) if url else ""
282
+ combined = "{}\n{}".format(str(title or ""), str(body_text or "")[:4000])
283
+ if has_security_modal or _SEC_VERIFY_URL_RE.search(href) or _SEC_VERIFY_TEXT_RE.search(combined):
284
+ return _es.PAGE_AUTH_SECURITY_VERIFY
285
+ if _SIGNED_OUT_URL_RE.search(href):
286
+ return _es.PAGE_AUTH_SIGNED_OUT
287
+ if has_login_modal or _LOGIN_WALL_TEXT_RE.search(combined):
288
+ return _es.PAGE_AUTH_SEARCH_RESTRICTED if after_search else _es.PAGE_AUTH_LOGIN_WALL
289
+ return _es.PAGE_AUTH_READY
290
+
291
+
292
+ def wait_for_stable_page_auth_state(
293
+ probe_fn,
294
+ *,
295
+ settle_s: float = 0.6,
296
+ interval_s: float = 0.25,
297
+ consecutive: int = 3,
298
+ max_samples: int = 7,
299
+ sleep_fn=time.sleep,
300
+ ) -> str:
301
+ """多帧防抖状态机:连续 consecutive 次观测一致才裁决,避免 SPA 水合瞬间误判。"""
302
+ import engine_states as _es
303
+
304
+ if settle_s > 0:
305
+ sleep_fn(settle_s)
306
+ last: str | None = None
307
+ repeated = 0
308
+ for idx in range(max(1, max_samples)):
309
+ current = probe_fn()
310
+ if current == last:
311
+ repeated += 1
312
+ else:
313
+ last = current
314
+ repeated = 1
315
+ if repeated >= max(1, consecutive):
316
+ return current
317
+ if interval_s > 0 and idx + 1 < max_samples:
318
+ sleep_fn(interval_s)
319
+ return last or _es.PAGE_AUTH_SIGNED_OUT
320
+
321
+
322
+ def verify_live_session(
323
+ url_or_host: str,
324
+ *,
325
+ cdp_factory=None,
326
+ timeout: float = 10.0,
327
+ settle_s: float = 0.6,
328
+ interval_s: float = 0.25,
329
+ ) -> dict:
330
+ """活体会话校验:确认持久 profile 存在且打开页面后经多帧防抖处于 PAGE_AUTH_READY。"""
331
+ import engine_states as _es
332
+
333
+ host = site_host(url_or_host)
334
+ prof = profile_for(host)
335
+ if not prof:
336
+ return {
337
+ "ok": False, "site": host, "state": _es.PAGE_AUTH_SIGNED_OUT,
338
+ "retryable": False, "handoff_required": True,
339
+ "error": f"未找到 {host} 的登录态 profile(请先 argo auth login {host})",
340
+ }
341
+ target = url_or_host.strip()
342
+ if "://" not in target:
343
+ target = "https://" + target
344
+
345
+ if cdp_factory is None:
346
+ from chrome_cdp import ChromeCDP
347
+ cdp_factory = lambda: ChromeCDP(auto_start=True, user_data_dir=prof)
348
+
349
+ cdp = None
350
+ try:
351
+ cdp = cdp_factory()
352
+ cdp.navigate(target, wait_until="networkidle", timeout=timeout)
353
+
354
+ def _probe() -> str:
355
+ return detect_page_auth_state(
356
+ cdp.get_url() or target,
357
+ cdp.get_title() or "",
358
+ cdp.get_text() or "",
359
+ )
360
+
361
+ state = wait_for_stable_page_auth_state(
362
+ _probe, settle_s=settle_s, interval_s=interval_s,
363
+ )
364
+ usable = _es.is_page_auth_usable(state)
365
+ non_retry = _es.is_page_auth_non_retryable(state)
366
+ return {
367
+ "ok": usable, "site": host, "state": state,
368
+ "retryable": not non_retry, "handoff_required": non_retry,
369
+ "error": None if usable else f"{host} 会话不可用(state={state}),请人工重新登录或通过验证",
370
+ }
371
+ except (OSError, RuntimeError, ValueError) as e:
372
+ return {
373
+ "ok": False, "site": host, "state": _es.PAGE_AUTH_SIGNED_OUT,
374
+ "retryable": True, "handoff_required": False,
375
+ "error": f"活体探测失败: {str(e)[:120]}",
376
+ }
377
+ finally:
378
+ if cdp is not None:
379
+ try:
380
+ cdp.stop()
381
+ except (OSError, RuntimeError):
382
+ pass
383
+
384
+
385
+ def bound_comments(
386
+ comments: list[dict],
387
+ *,
388
+ max_items: int = 30,
389
+ max_chars: int = 800,
390
+ ) -> dict:
391
+ """评论/回复上下文封顶器:最多保留 max_items 条,单条正文截断至 max_chars,显式标 truncated。"""
392
+ total = len(comments or [])
393
+ kept: list[dict] = []
394
+ truncated = total > max_items
395
+ for raw in (comments or [])[:max_items]:
396
+ if not isinstance(raw, dict):
397
+ continue
398
+ item = dict(raw)
399
+ for text_key in ("text", "content", "body"):
400
+ val = item.get(text_key)
401
+ if isinstance(val, str) and len(val) > max_chars:
402
+ item[text_key] = val[:max_chars] + "…"
403
+ truncated = True
404
+ kept.append(item)
405
+ return {"items": kept, "total": total, "truncated": truncated}
406
+
407
+
249
408
  # ─── CLI(bin/argo 的 auth 子命令入口)──────────────────────────────────────
250
409
 
251
410
  def main(argv: list[str] | None = None) -> None:
@@ -314,7 +473,22 @@ def main(argv: list[str] | None = None) -> None:
314
473
  print(f"删除失败:{out.get('error')}", file=sys.stderr)
315
474
  sys.exit(0 if out.get("ok") else 1)
316
475
 
317
- print(f"Unknown auth subcommand: {cmd}(可用:login / status / logout)",
476
+ if cmd == "verify":
477
+ if not rest:
478
+ print("用法:argo auth verify <url_or_host>(活体验证已保存会话)",
479
+ file=sys.stderr)
480
+ sys.exit(1)
481
+ out = verify_live_session(rest[0])
482
+ if use_json:
483
+ _emit_json(out)
484
+ elif out.get("ok"):
485
+ print(f"{out['site']} 登录态活体校验通过(state={out['state']})。")
486
+ else:
487
+ print(f"{out['site']} 校验未通过(state={out.get('state')}):{out.get('error')}",
488
+ file=sys.stderr)
489
+ sys.exit(0 if out.get("ok") else 1)
490
+
491
+ print(f"Unknown auth subcommand: {cmd}(可用:login / status / verify / logout)",
318
492
  file=sys.stderr)
319
493
  sys.exit(1)
320
494