@whyshu/argent-engine 0.8.0-rc.8 → 0.13.27

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 (113) hide show
  1. package/MANIFEST.json +109 -43
  2. package/bin/runtime-install.mjs +92 -0
  3. package/engine/VERSION +1 -1
  4. package/engine/configs/billing-actions.json +30 -0
  5. package/engine/configs/mcp-tools.snapshot.json +47 -0
  6. package/engine/core/contracts/argent.contracts.json +3 -3
  7. package/engine/core/contracts/verbs.schema.json +64 -1
  8. package/engine/core/lib/account-token.mjs +37 -0
  9. package/engine/core/lib/contract.mjs +30 -0
  10. package/engine/core/lib/redact.mjs +34 -0
  11. package/engine/core/mcp/billing-upload.mjs +77 -0
  12. package/engine/core/mcp/erp-server.mjs +300 -0
  13. package/engine/core/mcp/gateway.mjs +333 -0
  14. package/engine/core/mcp/meter.mjs +101 -0
  15. package/engine/core/mcp/server.mjs +416 -2
  16. package/engine/core/mcp/vault.mjs +78 -0
  17. package/engine/scripts/appointment-worker.mjs +456 -35
  18. package/engine/scripts/appointment_grab.py +1389 -264
  19. package/engine/scripts/appointment_rules.py +118 -0
  20. package/engine/scripts/argent-timers.mjs +227 -0
  21. package/engine/scripts/argent-web-preflight.mjs +123 -0
  22. package/engine/scripts/argent-web-verify.mjs +105 -0
  23. package/engine/scripts/billing-upload.mjs +26 -0
  24. package/engine/scripts/build-doc-index.mjs +68 -0
  25. package/engine/scripts/build-engine-package.mjs +7 -1
  26. package/engine/scripts/capability-packs.lock.json +323 -300
  27. package/engine/scripts/check-docs-drift.mjs +51 -4
  28. package/engine/scripts/check-version-consistency.mjs +14 -1
  29. package/engine/scripts/ci-run.sh +2 -2
  30. package/engine/scripts/collect-intel.mjs +108 -0
  31. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  32. package/engine/scripts/daily-report-timers.sh +36 -3
  33. package/engine/scripts/daily-report.mjs +78 -2
  34. package/engine/scripts/doc-status.mjs +212 -0
  35. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  36. package/engine/scripts/engine-manifest.mjs +90 -0
  37. package/engine/scripts/engine-runtime-install.mjs +92 -0
  38. package/engine/scripts/erp-ui-install.mjs +127 -0
  39. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  40. package/engine/scripts/erp-ui-verify.mjs +135 -0
  41. package/engine/scripts/flow-requirements.json +122 -99
  42. package/engine/scripts/full-exec-worker.mjs +251 -0
  43. package/engine/scripts/gen-preset-rows.mjs +1 -1
  44. package/engine/scripts/invoice_lip_runner.py +1 -0
  45. package/engine/scripts/invoice_runner.py +17 -6
  46. package/engine/scripts/invoice_stageb.py +21 -4
  47. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  48. package/engine/scripts/lib/intel-card.mjs +43 -0
  49. package/engine/scripts/lib/invoice_names.py +23 -0
  50. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  51. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  52. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  53. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  54. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  55. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  56. package/engine/scripts/lib/ml-items.mjs +40 -0
  57. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  58. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  59. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  60. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  61. package/engine/scripts/line_pack.py +196 -0
  62. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  63. package/engine/scripts/migrate-providers.mjs +3 -3
  64. package/engine/scripts/ml-ads-advice.mjs +140 -0
  65. package/engine/scripts/ml-ads.mjs +221 -0
  66. package/engine/scripts/ml-category-baseline.mjs +174 -0
  67. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  68. package/engine/scripts/ml-insight-run.sh +183 -0
  69. package/engine/scripts/ml-insight-timers.sh +224 -0
  70. package/engine/scripts/ml-listing-audit.mjs +170 -0
  71. package/engine/scripts/ml-market-matrix.mjs +84 -0
  72. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  73. package/engine/scripts/ml-messages.mjs +145 -0
  74. package/engine/scripts/ml-oauth-setup.mjs +1 -1
  75. package/engine/scripts/npm-publish-argent.mjs +14 -0
  76. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  77. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  78. package/engine/scripts/ops-digest.mjs +98 -0
  79. package/engine/scripts/ops-verify.mjs +67 -0
  80. package/engine/scripts/orchestrator.py +410 -20
  81. package/engine/scripts/orchestrator_br.py +146 -4
  82. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  83. package/engine/scripts/publish-engine.mjs +111 -0
  84. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  85. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  86. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  87. package/engine/scripts/vertical-lint.mjs +12 -1
  88. package/engine/scripts/web-switch.mjs +121 -0
  89. package/engine/scripts/wenyao_fill_template.py +52 -15
  90. package/engine/scripts/wenyao_run.py +2 -1
  91. package/engine/skills/README.md +3 -3
  92. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  93. package/engine/skills/douyin-upload/SKILL.md +74 -0
  94. package/engine/skills/internal.json +28 -0
  95. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  96. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  97. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  98. package/engine/skills/ml-invoice/SKILL.md +2 -2
  99. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  100. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  101. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  102. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  103. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  104. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  105. package/engine/skills/tencent-upload/SKILL.md +60 -0
  106. package/engine/skills/weibo-upload/SKILL.md +106 -0
  107. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  108. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  109. package/engine/version.mjs +1 -1
  110. package/engine/verticals/README.md +7 -0
  111. package/engine/verticals/_engine-words.baseline.txt +27 -59
  112. package/engine/verticals/mercadolibre/manifest.json +132 -6
  113. package/package.json +5 -1
@@ -61,6 +61,7 @@
61
61
  * 接进 CI 的是 `--matrix-only` 那一条(见 `scripts/ci-run.sh#CRITERIA`)。
62
62
  */
63
63
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
64
+ import { execFileSync } from 'node:child_process'
64
65
  import { dirname, join, relative, resolve, sep } from 'node:path'
65
66
  import { fileURLToPath } from 'node:url'
66
67
 
@@ -441,12 +442,58 @@ for (const rel of readmes) scanReadmeNumbers(join(ROOT, rel), rel, counts)
441
442
  // R4:宿主矩阵结构(**不随 --matrix-only 开关,永远跑** —— 它是结构性判据,任何模式下都该看得见)
442
443
  const matrix = scanHostMatrix(ROOT, HOST_MATRIX_REL)
443
444
 
445
+ // ── R5:文档状态(2026-11-02)—— frontmatter / superseded 指针 / INDEX 总览是否最新 ──
446
+ function scanDocStatus() {
447
+ const dir = join(ROOT, 'docs')
448
+ if (!existsSync(dir)) return
449
+ const walk = (d, base) => {
450
+ const out = []
451
+ for (const e of readdirSync(d)) {
452
+ if (e === 'archive') continue // 归档区不参与状态门禁
453
+ const p = join(d, e)
454
+ if (statSync(p).isDirectory()) out.push(...walk(p, join(base, e)))
455
+ else if (e.endsWith('.md') && e !== 'INDEX.md') out.push(join(base, e))
456
+ }
457
+ return out
458
+ }
459
+ for (const rel of walk(dir, 'docs')) {
460
+ const f = rel.split('/').pop()
461
+ const lines = readFileSync(join(ROOT, rel), 'utf8').split('\n')
462
+ const end = lines.indexOf('---', 1)
463
+ if (lines[0]?.trim() !== '---' || end < 0) {
464
+ push('R5', 'suspect', rel, 1, lines[0] || '', 'frontmatter',
465
+ '缺 frontmatter(status/appliesTo/updated)—— 约定见 docs/INDEX.md §文档状态约定')
466
+ continue
467
+ }
468
+ const fm = {}
469
+ for (const l of lines.slice(1, end)) {
470
+ const m = l.match(/^([A-Za-z]+):\s*(.*)$/)
471
+ if (m) fm[m[1]] = m[2].trim()
472
+ }
473
+ if (!fm.status) push('R5', 'suspect', rel, 1, '', 'status', 'frontmatter 缺 status')
474
+ if (fm.status === 'superseded') {
475
+ if (!fm.supersededBy) push('R5', 'suspect', rel, 1, '', 'supersededBy', 'superseded 文档必须给 supersededBy')
476
+ else if (!existsSync(join(ROOT, fm.supersededBy))) {
477
+ push('R5', 'suspect', rel, 1, fm.supersededBy, 'supersededBy', `supersededBy 指向不存在的文件:${fm.supersededBy}`)
478
+ }
479
+ }
480
+ }
481
+ try {
482
+ execFileSync(process.execPath, [join(ROOT, 'scripts', 'build-doc-index.mjs'), '--check'], { stdio: 'pipe' })
483
+ } catch {
484
+ push('R5', 'suspect', join('docs', 'INDEX.md'), 1, '', 'DOC-STATUS',
485
+ 'INDEX 状态总览过期:运行 node scripts/build-doc-index.mjs')
486
+ }
487
+ }
488
+ scanDocStatus()
489
+
444
490
  const suspects = findings.filter((f) => f.level === 'suspect')
445
491
  const infos = findings.filter((f) => f.level === 'info')
446
492
  const byRule = (lvl, rule) => findings.filter((f) => f.level === lvl && f.rule === rule).length
447
493
  const RULE_TITLE = {
448
494
  R1: 'R1 旧 dsh 版本号当现行', R2: 'R2 README 数字漂移',
449
495
  R3: 'R3 已废弃路径当现行', R4: 'R4 宿主矩阵结构(列数/空标签/状态符号)',
496
+ R5: 'R5 文档状态(frontmatter / superseded 指针 / INDEX 总览)',
450
497
  }
451
498
  const INFO_PRINT_PER_RULE = 12 // 每条规则的信息项逐条打印上限(避免刷屏;全量用 --json)
452
499
 
@@ -483,7 +530,7 @@ if (JSON_OUT) {
483
530
  console.log(` ${matrixSummary()} ← 文档:${HOST_MATRIX_REL}`)
484
531
  console.log('')
485
532
  console.log(`⚠️ 可疑 ${suspects.length} 条`)
486
- for (const rule of ['R1', 'R2', 'R3', 'R4']) {
533
+ for (const rule of ['R1', 'R2', 'R3', 'R4', 'R5']) {
487
534
  const list = suspects.filter((f) => f.rule === rule)
488
535
  if (!list.length) continue
489
536
  console.log(` ── ${RULE_TITLE[rule]}(${list.length} 条)`)
@@ -497,7 +544,7 @@ if (JSON_OUT) {
497
544
  console.log('')
498
545
  console.log(`ℹ️ 信息(历史/沿革语境,不计入可疑)${infos.length} 条`)
499
546
  let infoSkipped = 0
500
- for (const rule of ['R1', 'R2', 'R3', 'R4']) {
547
+ for (const rule of ['R1', 'R2', 'R3', 'R4', 'R5']) {
501
548
  const list = infos.filter((f) => f.rule === rule)
502
549
  if (!list.length) continue
503
550
  console.log(` ── ${RULE_TITLE[rule]}(${list.length} 条)`)
@@ -510,8 +557,8 @@ if (JSON_OUT) {
510
557
  console.log('')
511
558
  console.log(` =============================================`)
512
559
  console.log(` ${matrixSummary()}`)
513
- console.log(` 可疑 ${suspects.length} 条(R1=${byRule('suspect', 'R1')} / R2=${byRule('suspect', 'R2')} / R3=${byRule('suspect', 'R3')} / R4=${byRule('suspect', 'R4')})`
514
- + `|信息 ${infos.length} 条(R1=${byRule('info', 'R1')} / R2=${byRule('info', 'R2')} / R3=${byRule('info', 'R3')} / R4=${byRule('info', 'R4')})`)
560
+ console.log(` 可疑 ${suspects.length} 条(R1=${byRule('suspect', 'R1')} / R2=${byRule('suspect', 'R2')} / R3=${byRule('suspect', 'R3')} / R4=${byRule('suspect', 'R4')} / R5=${byRule('suspect', 'R5')})`
561
+ + `|信息 ${infos.length} 条(R1=${byRule('info', 'R1')} / R2=${byRule('info', 'R2')} / R3=${byRule('info', 'R3')} / R4=${byRule('info', 'R4')} / R5=${byRule('info', 'R5')})`)
515
562
  console.log(` 如何修:现行口径写**现役值**(dsh ${ACTIVE.version || '<现役版本>'}、路径 \`~/.local/node/bin\`、README 数字按实际计数),`
516
563
  + `历史内容**不要删**、只补「历史/升级记录」字样即可让本检查降级为信息;`
517
564
  + `矩阵结构(R4)另有修法:让出问题的行**回到表头的列数**(内容一格都不许丢)。`)
@@ -313,7 +313,20 @@ export function run(opts = {}) {
313
313
  // 目录级豁免会漏掉真·活引用(2026-10-10 实测:`scripts/tests/no-host-smoke.test.mjs` 曾把
314
314
  // 平台版本写死成字面量,正是本门禁要抓的那类)。
315
315
  const SELF_EXCLUDED = new Set([SELF, join(root, 'scripts', 'tests', 'version-consistency.test.mjs')].map((p) => resolve(p)))
316
- const scanned = files.filter((f) => !SELF_EXCLUDED.has(resolve(f)))
316
+ // 旧插件目录(2026-11-07 单插件合并后仅保留迁移兼容/开发夹具,不是客户入口):
317
+ // 其内部 <0.9 字面量按“历史兼容代码”显式豁免 R4;当前客户插件只看 plugins/argent/。
318
+ // ⛔ 这是一份**显式名单**,不是目录级通配;新增客户代码不得落进这些目录。
319
+ const LEGACY_PLUGIN_DIRS = [
320
+ 'plugins/argent-core', 'plugins/argent-desktop', 'plugins/argent-dsh',
321
+ 'plugins/argent-erp', 'plugins/argent-erp-ui', 'plugins/argent-flow',
322
+ 'plugins/argent-gateway', 'plugins/argent-ml', 'plugins/argent-presets',
323
+ 'plugins/argent-shell', 'plugins/argent-skin', 'plugins/argent-web',
324
+ ]
325
+ const isLegacyPlugin = (f) => {
326
+ const rel = relative(root, f).split(sep).join('/')
327
+ return LEGACY_PLUGIN_DIRS.some((d) => rel === d || rel.startsWith(`${d}/`))
328
+ }
329
+ const scanned = files.filter((f) => !SELF_EXCLUDED.has(resolve(f)) && !isLegacyPlugin(f))
317
330
  for (const f of scanned) {
318
331
  let text
319
332
  try { text = readFileSync(f, 'utf8') } catch { continue }
@@ -159,7 +159,7 @@ criterion_cmd() {
159
159
  1.0-criteria) printf '%s' 'node scripts/check-1.0-criteria.mjs --strict' ;;
160
160
  judgment-drift) printf '%s' 'node scripts/check-judgment-drift.mjs' ;;
161
161
  version-consistency) printf '%s' 'node scripts/check-version-consistency.mjs --strict' ;;
162
- contracts) printf '%s' 'node scripts/tests/argent-contracts.test.mjs' ;;
162
+ contracts) printf '%s' 'node scripts/tests/argent-contracts.test.mjs && node scripts/tests/two-artifact-contract.test.mjs' ;;
163
163
  capability-pack) printf '%s' "${PY} scripts/capability_pack.py --validate" ;;
164
164
  pack-closure) printf '%s' 'node scripts/check-pack-closure.mjs --strict' ;;
165
165
  config-catalog) printf '%s' 'node scripts/check-config-catalog.mjs --strict' ;;
@@ -187,7 +187,7 @@ criterion_expect() {
187
187
  1.0-criteria) printf '%s\n' '判据条数:40 条' '结论:✅ 一致' ;;
188
188
  judgment-drift) printf '%s\n' '契约漂移 0 条' ;;
189
189
  version-consistency) printf '%s\n' 'version-consistency: 0 个 error' ;;
190
- contracts) printf '%s\n' 'argent-contracts: [1-9][0-9]* 通过 / 0 失败' ;;
190
+ contracts) printf '%s\n' 'argent-contracts: [1-9][0-9]* 通过 / 0 失败' '契约测试:[1-9][0-9]* 通过 / 0 失败' ;;
191
191
  capability-pack) printf '%s\n' '每个能力包都自洽' ;;
192
192
  pack-closure) printf '%s\n' '缺件 0 个' ;;
193
193
  config-catalog) printf '%s\n' '四道门禁全绿' ;;
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 平台情报采集(0.10.0 P4)
4
+ *
5
+ * 用工具网关(whyshu `/api/argent/v1/tenants/:appId/tools/search`)取「平台政策 / 佣金 / 物流时效」
6
+ * 等公开信息,产出日报的 `intel[]`。
7
+ *
8
+ * ## 三条边界
9
+ * 1. **采集失败不阻断日报**:任何一条查询失败都只少一条情报,返回已拿到的部分;
10
+ * 2. **只用来"看",不用来"做"**:情报只进日报的展示段,⛔ 绝不用它驱动任何写操作;
11
+ * 3. **不做缓存**:政策有时效,缓存会让日报说三周前的规则。
12
+ *
13
+ * 用法(CLI):
14
+ * ARGENT_API_BASE=https://whyshu.com ARGENT_ACCOUNT_TOKEN=… ARGENT_TENANT=ly-0001 \
15
+ * node scripts/collect-intel.mjs --query "美客多 墨西哥 佣金" --json
16
+ */
17
+ import { fileURLToPath } from 'node:url'
18
+
19
+ /** 默认查询(可按业务线覆盖;⛔ 不含客户数据,只含公开话题) */
20
+ export const DEFAULT_QUERIES = [
21
+ '美客多 墨西哥站 佣金 费率 调整',
22
+ '美客多 墨西哥 物流 时效 旺季',
23
+ '墨西哥 跨境 税务 RFC 政策',
24
+ ]
25
+
26
+ /**
27
+ * @param {object} p
28
+ * @param {(q: string) => Promise<{ok:boolean, data?:object, message?:string}>} p.callSearch
29
+ * @param {string[]} [p.queries]
30
+ * @param {number} [p.perQuery] 每条查询取前几条
31
+ * @param {number} [p.limit] 总条数上限
32
+ */
33
+ export async function collectIntel({ callSearch, queries = DEFAULT_QUERIES, perQuery = 3, limit = 8 } = {}) {
34
+ if (typeof callSearch !== 'function') return { ok: false, items: [], errors: ['no_call_search'] }
35
+ const items = []
36
+ const seen = new Set()
37
+ const errors = []
38
+
39
+ for (const q of queries) {
40
+ let r
41
+ try {
42
+ r = await callSearch(q)
43
+ } catch (err) {
44
+ errors.push(`${q}: ${err?.message || err}`)
45
+ continue
46
+ }
47
+ if (!r || !r.ok) {
48
+ errors.push(`${q}: ${(r && (r.message || r.code)) || 'failed'}`)
49
+ continue
50
+ }
51
+ const results = (r.data && Array.isArray(r.data.results)) ? r.data.results : []
52
+ for (const it of results.slice(0, perQuery)) {
53
+ const key = it.url || it.title
54
+ if (!key || seen.has(key)) continue
55
+ seen.add(key)
56
+ items.push({
57
+ title: it.title || '',
58
+ url: it.url || '',
59
+ snippet: it.snippet || (it.summary || '').slice(0, 160),
60
+ site_name: it.site_name || '',
61
+ date: it.date || '',
62
+ })
63
+ if (items.length >= limit) return { ok: true, items, errors }
64
+ }
65
+ }
66
+ return { ok: true, items, errors }
67
+ }
68
+
69
+ /** 默认搜索实现:走工具网关(令牌来自 env;⛔ 不落盘、不打日志) */
70
+ export function makeDefaultCallSearch({
71
+ apiBase = process.env.ARGENT_API_BASE || 'https://whyshu.com',
72
+ tenant = process.env.ARGENT_TENANT || '',
73
+ token = process.env.ARGENT_ACCOUNT_TOKEN || '',
74
+ fetchImpl = globalThis.fetch,
75
+ } = {}) {
76
+ return async function callSearch(query) {
77
+ if (!tenant || !token) return { ok: false, code: 'no_credentials', message: '缺少 ARGENT_TENANT / ARGENT_ACCOUNT_TOKEN' }
78
+ const url = `${String(apiBase).replace(/\/+$/, '')}/api/argent/v1/tenants/${encodeURIComponent(tenant)}/tools/search`
79
+ try {
80
+ const res = await fetchImpl(url, {
81
+ method: 'POST',
82
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
83
+ body: JSON.stringify({ query, count: 5 }),
84
+ })
85
+ const body = await res.json().catch(() => null)
86
+ if (!res.ok) return { ok: false, code: body?.error?.code || `http_${res.status}`, message: body?.error?.message }
87
+ return { ok: true, data: body?.data, billing: body?.billing }
88
+ } catch (err) {
89
+ return { ok: false, code: 'unreachable', message: String(err?.message || err) }
90
+ }
91
+ }
92
+ }
93
+
94
+ // ── CLI ─────────────────────────────────────────────
95
+ const isDirect = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]
96
+ if (isDirect) {
97
+ const argv = process.argv.slice(2)
98
+ const getArg = (n, d) => { const i = argv.indexOf(n); return i > -1 ? argv[i + 1] : d }
99
+ const qs = argv.includes('--query') ? [getArg('--query')] : DEFAULT_QUERIES
100
+ const out = await collectIntel({ callSearch: makeDefaultCallSearch(), queries: qs })
101
+ if (argv.includes('--json')) {
102
+ console.log(JSON.stringify(out, null, 2))
103
+ } else {
104
+ if (!out.ok) console.error(`✗ 采集失败:${out.errors.join(';')}`)
105
+ for (const it of out.items) console.log(`- ${it.title} ${it.url}`)
106
+ if (out.errors.length) console.error(`⚠️ 部分查询失败:${out.errors.join(';')}`)
107
+ }
108
+ }
@@ -9,6 +9,10 @@
9
9
  # 用法(只打印,不写文件、不碰 launchctl):
10
10
  # bash scripts/daily-report-timer-plist.sh --label <label> --script <abs path>
11
11
  # --data-dir <dir> --log-dir <dir> [--node-dir <dir>] [--lark-dir <dir>] [--minute <0-59>] [--hour <0-23>]
12
+ # [--log-name <name>] [--arg <v>]...
13
+ #
14
+ # 2026-11-20(零命令化批次 B):新增 `--log-name`(默认 daily-report-timer,**默认输出逐字节不变**)
15
+ # 与可重复的 `--arg`(追加到 ProgramArguments,供 ml-listing/ml-market 定时器传子命令)。
12
16
  #
13
17
  # 关键约定:
14
18
  # · `StartCalendarInterval{Minute:5}`(+ 默认不带 Hour)= **每小时的第 5 分钟**跑一次;
@@ -19,7 +23,7 @@
19
23
  # · `ARGENT_DATA_DIR` —— 数据根**由调用方按唯一判据解析**后传入(⛔ 本文件不拼 `~/.dsh/argent`)。
20
24
  set -euo pipefail
21
25
 
22
- LABEL=""; SCRIPT=""; DATA_DIR=""; LOG_DIR=""; NODE_DIR=""; LARK_DIR=""; MINUTE="5"; HOUR=""
26
+ LABEL=""; SCRIPT=""; DATA_DIR=""; LOG_DIR=""; NODE_DIR=""; LARK_DIR=""; MINUTE="5"; HOUR=""; LOG_NAME="daily-report-timer"; ARGS=()
23
27
  while [ $# -gt 0 ]; do
24
28
  case "$1" in
25
29
  --label) LABEL="${2:-}"; shift 2;;
@@ -30,6 +34,8 @@ while [ $# -gt 0 ]; do
30
34
  --lark-dir) LARK_DIR="${2:-}"; shift 2;;
31
35
  --minute) MINUTE="${2:-}"; shift 2;;
32
36
  --hour) HOUR="${2:-}"; shift 2;;
37
+ --log-name) LOG_NAME="${2:-}"; shift 2;;
38
+ --arg) ARGS+=("${2:-}"); shift 2;;
33
39
  -h|--help) sed -n '2,22p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0;;
34
40
  *) echo "未知参数: $1" >&2; exit 2;;
35
41
  esac
@@ -41,6 +47,8 @@ done
41
47
  [ -n "$LOG_DIR" ] || { echo "缺 --log-dir(⛔ 同上)" >&2; exit 2; }
42
48
  case "$MINUTE" in ''|*[!0-9]*) echo "--minute 必须是 0-59 的整数" >&2; exit 2;; esac
43
49
  case "$HOUR" in '') : ;; ''|*[!0-9]*) echo "--hour 必须是 0-23 的整数(不给=每小时)" >&2; exit 2;; esac
50
+ [ -n "$LOG_NAME" ] || { echo "缺 --log-name" >&2; exit 2; }
51
+ if [ "${#ARGS[@]}" -gt 0 ]; then for a in "${ARGS[@]}"; do [ -n "$a" ] || { echo "--arg 不能为空" >&2; exit 2; }; done; fi
44
52
  NODE_DIR="${NODE_DIR:-$(dirname "$(command -v node || echo /usr/local/bin/node)")}"
45
53
  LARK_DIR="${LARK_DIR:-$(dirname "$(command -v lark-cli || echo /usr/local/bin/lark-cli)")}"
46
54
 
@@ -48,6 +56,12 @@ xml_escape() { printf '%s' "$1" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g';
48
56
 
49
57
  HOUR_XML=""
50
58
  [ -n "$HOUR" ] && printf -v HOUR_XML ' <key>Hour</key>\n <integer>%s</integer>\n' "$HOUR"
59
+ ARGS_XML=""
60
+ if [ "${#ARGS[@]}" -gt 0 ]; then
61
+ for a in "${ARGS[@]}"; do
62
+ ARGS_XML+=" <string>$(xml_escape "$a")</string>"$'\n'
63
+ done
64
+ fi
51
65
 
52
66
  cat <<PLIST
53
67
  <?xml version="1.0" encoding="UTF-8"?>
@@ -61,7 +75,7 @@ cat <<PLIST
61
75
  <array>
62
76
  <string>/bin/bash</string>
63
77
  <string>$(xml_escape "$SCRIPT")</string>
64
- </array>
78
+ ${ARGS_XML} </array>
65
79
  <key>StartCalendarInterval</key>
66
80
  <dict>
67
81
  ${HOUR_XML} <key>Minute</key>
@@ -79,9 +93,9 @@ ${HOUR_XML} <key>Minute</key>
79
93
  <string>$(xml_escape "$NODE_DIR:$LARK_DIR:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin")</string>
80
94
  </dict>
81
95
  <key>StandardOutPath</key>
82
- <string>$(xml_escape "$LOG_DIR/daily-report-timer.out.log")</string>
96
+ <string>$(xml_escape "$LOG_DIR/$LOG_NAME.out.log")</string>
83
97
  <key>StandardErrorPath</key>
84
- <string>$(xml_escape "$LOG_DIR/daily-report-timer.err.log")</string>
98
+ <string>$(xml_escape "$LOG_DIR/$LOG_NAME.err.log")</string>
85
99
  <key>WorkingDirectory</key>
86
100
  <string>$(xml_escape "$HOME")</string>
87
101
  </dict>
@@ -10,7 +10,7 @@
10
10
  # 用法:
11
11
  # bash scripts/daily-report-timers.sh status # 状态(launchd + 状态文件一行)
12
12
  # bash scripts/daily-report-timers.sh print-plist # 只打印 plist(不写、不装)
13
- # bash scripts/daily-report-timers.sh install [--dry-run] [--force]
13
+ # bash scripts/daily-report-timers.sh install [--dry-run] [--force] [--allow-non-production]
14
14
  # bash scripts/daily-report-timers.sh uninstall
15
15
  # bash scripts/daily-report-timers.sh run-now [daily-report.mjs 参数…] # 手工跑一轮(补推用)
16
16
  #
@@ -71,11 +71,44 @@ require_runtime() {
71
71
  }
72
72
 
73
73
  cmd_install() {
74
- local dry=0 force=0
74
+ local dry=0 force=0 allow_np=0
75
75
  case " $* " in *" --dry-run "*) dry=1;; esac
76
76
  case " $* " in *" --force "*) force=1;; esac
77
+ case " $* " in *" --allow-non-production "*) allow_np=1;; esac
77
78
  require_runtime
78
79
 
80
+ # 2026-11-02 事故后固化:**非生产机默认不许装日报定时器**
81
+ # 事故:开发机装了定时器并手动跑一轮 ⇒ 一条真实日报推进了客户群。
82
+ # 放行条件(任一):dailyReport.role=production | allowedChatIds 非空 | 显式 --allow-non-production
83
+ if [ "$allow_np" != 1 ]; then
84
+ local role allow
85
+ role="$(/usr/bin/python3 - "$DATA_HOME/config.json" <<'PYEOF' 2>/dev/null || true
86
+ import json,sys
87
+ try:
88
+ d=json.load(open(sys.argv[1])); print((d.get('dailyReport') or {}).get('role',''))
89
+ except Exception: print('')
90
+ PYEOF
91
+ )"
92
+ allow="$(/usr/bin/python3 - "$DATA_HOME/config.json" <<'PYEOF' 2>/dev/null || true
93
+ import json,sys
94
+ try:
95
+ d=json.load(open(sys.argv[1])); print(len((d.get('dailyReport') or {}).get('allowedChatIds') or []))
96
+ except Exception: print(0)
97
+ PYEOF
98
+ )"
99
+ if [ "$role" != "production" ] && [ "${allow:-0}" = "0" ]; then
100
+ cat >&2 <<EOF
101
+ ❌ 拒绝安装:本机不是日报生产机(dailyReport.role=${role:-未声明},allowedChatIds=${allow:-0} 条)
102
+ · 装上去就会**按站点时间真推客户群**——2026-11-02 就这么误推过一条。
103
+ · 只在开发机上验证请用:node scripts/daily-report.mjs --dry-run(或 --json,不发消息)
104
+ · 确实要在这台机器上装(例如内部测试群):config.json 写
105
+ "dailyReport": { "role": "production", "allowedChatIds": ["oc_测试群"] }
106
+ 或显式加 --allow-non-production(自己承担后果)
107
+ EOF
108
+ exit 3
109
+ fi
110
+ fi
111
+
79
112
  if old_trigger_loaded || [ -f "$OLD_PLIST" ]; then
80
113
  if [ "$force" != 1 ]; then
81
114
  cat >&2 <<EOF
@@ -112,7 +145,7 @@ EOF
112
145
  echo "✅ 已安装并加载:${LABEL}(每小时 :05 跑 ${RUNNER})"
113
146
  else
114
147
  echo "⚠️ plist 已写入但 bootstrap 失败:$PLIST" >&2
115
- echo " 排查:launchctl print gui/$(id -u)/$LABEL|launchctl error <码>" >&2
148
+ echo " 排查:launchctl print gui/$(id -u)/${LABEL}|launchctl error <码>" >&2
116
149
  exit 1
117
150
  fi
118
151
  echo " 状态文件:$DATA_HOME/daily-report-timer-status.json"
@@ -27,6 +27,7 @@
27
27
  */
28
28
 
29
29
  import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync, appendFileSync, accessSync } from 'node:fs'
30
+ import { intelCardBlocks } from './lib/intel-card.mjs'
30
31
  import { homedir } from 'node:os'
31
32
  import { join, dirname } from 'node:path'
32
33
  import { fileURLToPath } from 'node:url'
@@ -909,6 +910,34 @@ function larkConfig() {
909
910
  } catch { return {} }
910
911
  }
911
912
 
913
+ /**
914
+ * 推送目标守卫(2026-11-02 事故后固化)——**默认拒绝**,必须显式放行。
915
+ *
916
+ * 事故:开发机上装定时器 + 手动跑一轮,把一条真实日报推进了客户群(六禾园智能体)。
917
+ * 根因不是权限,是"任何机器都能往任何群推"。故改成 fail-closed:
918
+ * 放行条件(任一):`ARGENT_ALLOW_CUSTOMER_PUSH=1` | cfg.dailyReport.role === 'production'
919
+ * | chatId ∈ cfg.dailyReport.allowedChatIds
920
+ * 其余一律拒绝,并在错误里给出放行办法(⛔ 不静默跳过,必须让人看见)。
921
+ */
922
+ export function pushTargetAllowed({ chatId = '', cfg = {}, env = process.env } = {}) {
923
+ const dr = (cfg && cfg.dailyReport) || {}
924
+ if (String(env.ARGENT_ALLOW_CUSTOMER_PUSH || '') === '1') return { ok: true, reason: 'env-override' }
925
+ if (Array.isArray(dr.allowedChatIds) && dr.allowedChatIds.length) {
926
+ return dr.allowedChatIds.includes(String(chatId))
927
+ ? { ok: true, reason: 'allowlist' }
928
+ : { ok: false, reason: 'not-in-allowlist', detail: `目标群 ${chatId} 不在 dailyReport.allowedChatIds 里` }
929
+ }
930
+ if (String(dr.role || '').toLowerCase() === 'production') return { ok: true, reason: 'production-role' }
931
+ const role = String(dr.role || '').trim()
932
+ return {
933
+ ok: false,
934
+ reason: 'no-role-and-no-allowlist',
935
+ detail: role
936
+ ? `本机 dailyReport.role=${role}(不是 production),也没配 allowedChatIds ⇒ 禁止向客户群推送`
937
+ : '本机未声明 dailyReport.role=production,也没有 allowedChatIds ⇒ 禁止向客户群推送',
938
+ }
939
+ }
940
+
912
941
  // 读取链:Web 配置中心 config.json(mlDaily*)→ daily-report.env(旧键)→ 默认
913
942
  export function pick(cfg, env, cfgKey, envKey, def) {
914
943
  const v = cfg[cfgKey] ?? env[envKey]
@@ -977,6 +1006,7 @@ function pushLark(md, chatId, profile) {
977
1006
  if (r.status !== 0) {
978
1007
  throw new Error(`lark-cli 推送失败: ${(r.error?.message || r.stderr || r.stdout || '').slice(0, 300)}`)
979
1008
  }
1009
+ return larkMessageId(r.stdout)
980
1010
  }
981
1011
 
982
1012
  // 2026-08-31:lark-bot 通道改发 interactive 卡片(与 webhook 卡片同构,角色化后保持卡片式)
@@ -989,6 +1019,18 @@ function pushLarkCard(card, chatId, profile) {
989
1019
  if (r.status !== 0) {
990
1020
  throw new Error(`lark-cli 卡片推送失败: ${(r.error?.message || r.stderr || r.stdout || '').slice(0, 300)}`)
991
1021
  }
1022
+ return larkMessageId(r.stdout)
1023
+ }
1024
+
1025
+ /**
1026
+ * 从 lark-cli 的 stdout 取 message_id(2026-11-02:**推完必须记得住 id**,
1027
+ * 否则事后要撤回却拿不到 id —— 客户机 bot 也没有 im:message:readonly 列不了消息)。
1028
+ */
1029
+ function larkMessageId(stdout) {
1030
+ try {
1031
+ const d = JSON.parse(String(stdout || ''))
1032
+ return (d && ((d.data && d.data.message_id) || d.message_id)) || ''
1033
+ } catch { return '' }
992
1034
  }
993
1035
 
994
1036
  /** 上传结构化日报到 ERP(bridge secret;失败不阻断群推送,ERP 页显示上一份)。 */
@@ -1025,8 +1067,21 @@ async function pushCards(env, cards, overview) {
1025
1067
  if (overview) await pushWebhook(webhook, overview)
1026
1068
  return 'webhook'
1027
1069
  }
1028
- for (const c of cards) pushLarkCard(c.card, chatId, profile) // 每店一张卡(用户决策 D)
1029
- if (overview) pushLarkCard(overview.card, chatId, profile)
1070
+ const gate = pushTargetAllowed({ chatId, cfg, env })
1071
+ if (!gate.ok) {
1072
+ throw new Error(`⛔ 拒绝推送(${gate.reason}):${gate.detail || ''}`
1073
+ + ' | 放行办法:本机 config.json → dailyReport.allowedChatIds 加该群,或显式 ARGENT_ALLOW_CUSTOMER_PUSH=1')
1074
+ }
1075
+ const ids = []
1076
+ for (const c of cards) ids.push(pushLarkCard(c.card, chatId, profile)) // 每店一张卡(用户决策 D)
1077
+ if (overview) ids.push(pushLarkCard(overview.card, chatId, profile))
1078
+ // 记住 id(撤回/审计用);失败不阻断推送
1079
+ try {
1080
+ writeFileSync(join(DATA_DIR, 'daily-report-last-push.json'), JSON.stringify({
1081
+ at: new Date().toISOString(), chatId, profile, messageIds: ids.filter(Boolean),
1082
+ }, null, 2) + '\n')
1083
+ } catch { /* 写不进去不影响推送 */ }
1084
+ if (ids.filter(Boolean).length) console.log(`[daily-report] 本次消息 id:${ids.filter(Boolean).join(', ')}`)
1030
1085
  return 'lark-bot-card'
1031
1086
  }
1032
1087
 
@@ -1620,6 +1675,24 @@ async function main() {
1620
1675
  return 0
1621
1676
  }
1622
1677
 
1678
+ // 平台情报(**默认关**):ARGENT_DAILY_INTEL=1 才采集。
1679
+ // 为什么默认关:每次日报会多花几次搜索的钱,且会多推一张卡 —— 属于"客户明确要才开"的行为。
1680
+ let intel = []
1681
+ if (/^(1|true|yes)$/i.test(String(env.ARGENT_DAILY_INTEL || ''))) {
1682
+ try {
1683
+ const { collectIntel, makeDefaultCallSearch } = await import('./collect-intel.mjs')
1684
+ const r = await collectIntel({
1685
+ callSearch: makeDefaultCallSearch({
1686
+ apiBase: env.ARGENT_API_BASE, tenant: env.ARGENT_TENANT, token: env.ARGENT_ACCOUNT_TOKEN,
1687
+ }),
1688
+ })
1689
+ intel = r.items || []
1690
+ if (r.errors && r.errors.length) console.error(`[daily-report] 情报部分失败:${r.errors.join(';')}`)
1691
+ } catch (e) {
1692
+ console.error(`[daily-report] 情报采集失败(不影响日报):${e.message || e}`)
1693
+ }
1694
+ }
1695
+
1623
1696
  try {
1624
1697
  const payload = buildReportPayload({ dateLabel, blocksList, failed })
1625
1698
  // ERP 完整日报先上传;失败只告警,不阻断群推送
@@ -1642,6 +1715,9 @@ async function main() {
1642
1715
  overview = cardMessageV2(`📊 美客多日报 · ${dateLabel}|跨店总览`, buildOverviewBlocks(dateLabel, items),
1643
1716
  { template: items.some((x) => x.level === 'red') ? 'red' : items.some((x) => x.level === 'yellow') ? 'yellow' : 'green' })
1644
1717
  }
1718
+ if (intel.length) {
1719
+ cards.push(cardMessageV2(`🔎 平台情报 · ${dateLabel}`, intelCardBlocks(intel), { template: 'blue' }))
1720
+ }
1645
1721
  if (failed.length && !useTable) {
1646
1722
  cards.push(cardMessageV2(`⚠️ 美客多日报 · ${dateLabel}|部分店铺未取到`, {
1647
1723
  head: [`**以下店铺本轮采集失败**(其余店铺正常)`, ''],