@whyshu/argent-engine 0.8.0-rc.13 → 0.8.0-rc.15
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/MANIFEST.json +71 -36
- package/engine/VERSION +1 -1
- package/engine/configs/mcp-tools.snapshot.json +8 -1
- package/engine/core/contracts/argent.contracts.json +2 -2
- package/engine/core/mcp/erp-server.mjs +10 -6
- package/engine/core/mcp/gateway.mjs +3 -3
- package/engine/core/mcp/server.mjs +245 -0
- package/engine/scripts/appointment-worker.mjs +456 -35
- package/engine/scripts/appointment_grab.py +1329 -284
- package/engine/scripts/appointment_rules.py +118 -0
- package/engine/scripts/argent-timers.mjs +227 -0
- package/engine/scripts/capability-packs.lock.json +323 -300
- package/engine/scripts/check-version-consistency.mjs +14 -1
- package/engine/scripts/collect-intel.mjs +108 -0
- package/engine/scripts/daily-report-timer-plist.sh +18 -4
- package/engine/scripts/daily-report-timers.sh +1 -1
- package/engine/scripts/daily-report.mjs +22 -0
- package/engine/scripts/engine-manifest.mjs +90 -0
- package/engine/scripts/flow-requirements.json +122 -99
- package/engine/scripts/full-exec-worker.mjs +251 -0
- package/engine/scripts/gen-preset-rows.mjs +1 -1
- package/engine/scripts/invoice_lip_runner.py +1 -0
- package/engine/scripts/invoice_runner.py +3 -1
- package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
- package/engine/scripts/lib/intel-card.mjs +43 -0
- package/engine/scripts/lib/invoice_names.py +23 -0
- package/engine/scripts/lib/ml-ads-core.mjs +100 -18
- package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
- package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
- package/engine/scripts/lib/ml-category-core.mjs +120 -0
- package/engine/scripts/lib/ml-insight-core.mjs +621 -0
- package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
- package/engine/scripts/lib/ml-items.mjs +40 -0
- package/engine/scripts/lib/ml-listing-core.mjs +342 -0
- package/engine/scripts/lib/ml-market-core.mjs +774 -0
- package/engine/scripts/lib/webdriver_ipc.py +61 -1
- package/engine/scripts/line_pack.py +196 -0
- package/engine/scripts/ml-ads-advice.mjs +140 -0
- package/engine/scripts/ml-ads.mjs +40 -0
- package/engine/scripts/ml-category-baseline.mjs +174 -0
- package/engine/scripts/ml-insight-diagnose.mjs +247 -0
- package/engine/scripts/ml-insight-run.sh +183 -0
- package/engine/scripts/ml-insight-timers.sh +224 -0
- package/engine/scripts/ml-listing-audit.mjs +170 -0
- package/engine/scripts/ml-market-matrix.mjs +84 -0
- package/engine/scripts/ml-market-snapshot.mjs +261 -0
- package/engine/scripts/ml-messages.mjs +145 -0
- package/engine/scripts/npm-publish-argent.mjs +14 -0
- package/engine/scripts/ops-codefix-pr.mjs +87 -0
- package/engine/scripts/ops-codefix-queue.mjs +30 -0
- package/engine/scripts/ops-digest.mjs +98 -0
- package/engine/scripts/ops-verify.mjs +67 -0
- package/engine/scripts/orchestrator.py +410 -20
- package/engine/scripts/orchestrator_br.py +146 -4
- package/engine/scripts/plugin-bootcheck.mjs +50 -1
- package/engine/scripts/publish-engine.mjs +111 -0
- package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
- package/engine/scripts/skuflow_invoice_runner.py +24 -3
- package/engine/scripts/vertical-lint.mjs +12 -1
- package/engine/scripts/wenyao_fill_template.py +52 -15
- package/engine/scripts/wenyao_run.py +2 -1
- package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
- package/engine/skills/ml-full-appointment/SKILL.md +23 -0
- package/engine/skills/ml-invoice/SKILL.md +2 -2
- package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
- package/engine/skills/ml-label-recovery/SKILL.md +43 -0
- package/engine/skills/ml-listing-audit/SKILL.md +66 -0
- package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
- package/engine/skills/ml-store-insight/SKILL.md +81 -0
- package/engine/version.mjs +1 -1
- package/engine/verticals/README.md +7 -0
- package/engine/verticals/_engine-words.baseline.txt +27 -59
- package/engine/verticals/mercadolibre/manifest.json +132 -6
- package/package.json +1 -1
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""抢预约「时间规则」在引擎侧的编译(2026-11-19)。
|
|
2
|
+
|
|
3
|
+
与 ERP `appointmentRuleService.compileRulePreview` 同一口径:
|
|
4
|
+
· 工作日 = 周一至周五(周末不计入「工作日后 N 天」)
|
|
5
|
+
· leadWorkdays=0 从今天开始;N>0 往后数 N 个工作日
|
|
6
|
+
· dailyAdvanceAt 到点后起点 +1 天(按墨西哥时间)
|
|
7
|
+
· horizonDays 只约 N 天内(含起点)
|
|
8
|
+
· windows 按 ISO 周几(1=周一…7=周日)配置,可多段;空=当天不约
|
|
9
|
+
· skipDates 跳过
|
|
10
|
+
|
|
11
|
+
平台时区固定 America/Mexico_City = UTC-6(墨西哥 2022 年起无夏令时),
|
|
12
|
+
引擎运行在客户机(中国时区)⇒ 所有“今天/到点判断”都必须走本模块,⛔ 不用本机时间。
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from datetime import date, datetime, timedelta, timezone
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
MX_TZ = timezone(timedelta(hours=-6))
|
|
20
|
+
_WD_CACHE: dict[str, Any] = {}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def mexico_now(now: datetime | None = None) -> datetime:
|
|
24
|
+
if now is None:
|
|
25
|
+
return datetime.now(MX_TZ)
|
|
26
|
+
if now.tzinfo is None:
|
|
27
|
+
return now.replace(tzinfo=MX_TZ)
|
|
28
|
+
return now.astimezone(MX_TZ)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _minutes(hhmm: str) -> int | None:
|
|
32
|
+
try:
|
|
33
|
+
h, m = str(hhmm).split(':')[:2]
|
|
34
|
+
return int(h) * 60 + int(m)
|
|
35
|
+
except Exception:
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _is_workday(d: date, skip: set[str]) -> bool:
|
|
40
|
+
return d.isoweekday() <= 5 and d.isoformat() not in skip
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def compile_rule(spec: dict | None, today: date, *, now: datetime | None = None) -> dict[str, list[dict]]:
|
|
44
|
+
"""返回 {YYYY-MM-DD: [{from, to}, ...]};空 dict = 当前没有可约日期。"""
|
|
45
|
+
spec = spec if isinstance(spec, dict) else {}
|
|
46
|
+
skip = {str(x) for x in (spec.get('skipDates') or []) if str(x)}
|
|
47
|
+
try:
|
|
48
|
+
lead = max(0, int(spec.get('leadWorkdays') or 0))
|
|
49
|
+
except Exception:
|
|
50
|
+
lead = 0
|
|
51
|
+
try:
|
|
52
|
+
horizon = max(1, int(spec.get('horizonDays') or 7))
|
|
53
|
+
except Exception:
|
|
54
|
+
horizon = 7
|
|
55
|
+
windows = spec.get('windows') or {}
|
|
56
|
+
advance_raw = str(spec.get('dailyAdvanceAt') or '').strip()
|
|
57
|
+
advance = _minutes(advance_raw) if advance_raw else None
|
|
58
|
+
clock = mexico_now(now)
|
|
59
|
+
|
|
60
|
+
start = today
|
|
61
|
+
if lead > 0:
|
|
62
|
+
counted = 0
|
|
63
|
+
while counted < lead:
|
|
64
|
+
start = start + timedelta(days=1)
|
|
65
|
+
if _is_workday(start, skip):
|
|
66
|
+
counted += 1
|
|
67
|
+
if advance is not None and (clock.hour * 60 + clock.minute) >= advance:
|
|
68
|
+
start = start + timedelta(days=1)
|
|
69
|
+
|
|
70
|
+
out: dict[str, list[dict]] = {}
|
|
71
|
+
for i in range(horizon):
|
|
72
|
+
d = start + timedelta(days=i)
|
|
73
|
+
key = d.isoformat()
|
|
74
|
+
if key in skip:
|
|
75
|
+
continue
|
|
76
|
+
raw = windows.get(d.isoweekday()) or windows.get(str(d.isoweekday())) or []
|
|
77
|
+
segs: list[dict] = []
|
|
78
|
+
for seg in raw if isinstance(raw, list) else []:
|
|
79
|
+
frm = str((seg or {}).get('from') or '').strip()
|
|
80
|
+
to = str((seg or {}).get('to') or '').strip()
|
|
81
|
+
fm, tm = _minutes(frm), _minutes(to)
|
|
82
|
+
if fm is None or tm is None or fm >= tm:
|
|
83
|
+
continue
|
|
84
|
+
segs.append({'from': frm, 'to': to})
|
|
85
|
+
if segs:
|
|
86
|
+
out[key] = segs
|
|
87
|
+
return out
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def targets(spec: dict | None, today: date, *, now: datetime | None = None) -> list[date]:
|
|
91
|
+
return sorted(date.fromisoformat(k) for k in compile_rule(spec, today, now=now))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def slot_datetime(date_iso: str, slot_text: str) -> datetime | None:
|
|
95
|
+
"""把平台日期+时段文本(9:45 / 09:45)转成墨西哥绝对时间;解析失败返回 None。"""
|
|
96
|
+
try:
|
|
97
|
+
base = date.fromisoformat(str(date_iso)[:10])
|
|
98
|
+
except ValueError:
|
|
99
|
+
return None
|
|
100
|
+
import re
|
|
101
|
+
m = re.search(r'(\d{1,2})\s*[::.]\s*(\d{2})', str(slot_text or ''))
|
|
102
|
+
if not m:
|
|
103
|
+
return None
|
|
104
|
+
return datetime(base.year, base.month, base.day, int(m.group(1)), int(m.group(2)), tzinfo=MX_TZ)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def min_lead_ok(date_iso: str, slot_text: str, min_hours: float, *, now: datetime | None = None) -> bool:
|
|
108
|
+
"""预约绝对时间是否 ≥ 现在 + 至少提前小时数。无法解析的时段不拦(交给页面真实时段判断)。"""
|
|
109
|
+
try:
|
|
110
|
+
hours = float(min_hours or 0)
|
|
111
|
+
except Exception:
|
|
112
|
+
hours = 0
|
|
113
|
+
if hours <= 0:
|
|
114
|
+
return True
|
|
115
|
+
dt = slot_datetime(date_iso, slot_text)
|
|
116
|
+
if dt is None:
|
|
117
|
+
return True
|
|
118
|
+
return dt >= mexico_now(now) + timedelta(hours=hours)
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* argent-timers.mjs —— **系统定时器清单(只读)**:launchctl 在册 + plist 排程 + 状态文件。
|
|
4
|
+
*
|
|
5
|
+
* 为什么需要它(2026-11-20):
|
|
6
|
+
* · 客户机上 argent 会装多条 LaunchAgent(worker / 日报 / Listing 体检 / 竞品快照…),
|
|
7
|
+
* 还有历史残留(flow-trigger / fulfillment-poll)—— 客户"到底有几条、哪条停了"没有单一出口;
|
|
8
|
+
* · 桌宠健康只显示"日报定时器"一条;ERP 控制台没有定时器视图。
|
|
9
|
+
* 本 CLI 是**唯一取数口**:MCP 工具 `argent_timers` 调它,将来 ERP 机器心跳也复用它。
|
|
10
|
+
*
|
|
11
|
+
* 纪律:
|
|
12
|
+
* · **只读**:只读 launchctl 输出 / plist 文件 / 状态 JSON;⛔ 不 bootstrap/bootout、不写任何文件;
|
|
13
|
+
* · 判据可注入(`--launchctl-file` / `--plist-dir` / `--data-dir`)⇒ 离线可回归;
|
|
14
|
+
* · 失败不静默:launchctl 不可用 ⇒ `ok:false` + 原因;单条 plist 读不了 ⇒ 该条 `schedule:null` + note。
|
|
15
|
+
*
|
|
16
|
+
* 用法:
|
|
17
|
+
* node scripts/argent-timers.mjs # 人读
|
|
18
|
+
* node scripts/argent-timers.mjs --json # 结构化(MCP / ERP 心跳复用)
|
|
19
|
+
* node scripts/argent-timers.mjs --json --launchctl-file /tmp/launchctl.txt --plist-dir /tmp/plists --data-dir /tmp/data
|
|
20
|
+
*/
|
|
21
|
+
import { execFileSync } from 'node:child_process'
|
|
22
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs'
|
|
23
|
+
import { homedir } from 'node:os'
|
|
24
|
+
import { join } from 'node:path'
|
|
25
|
+
import { pathToFileURL } from 'node:url'
|
|
26
|
+
import { resolveDataDir } from './lib/argent-datadir.mjs'
|
|
27
|
+
|
|
28
|
+
/** 已知 label 的释义与归属(未知 label 也照实列出,⛔ 不丢)。 */
|
|
29
|
+
export const KNOWN_LABELS = Object.freeze({
|
|
30
|
+
'com.whyshu.appointment-worker': { desc: '抢预约 worker(常驻)', kind: 'worker' },
|
|
31
|
+
'com.whyshu.full-booking-worker': { desc: 'FULL 自动预约 worker(full 模式)', kind: 'worker' },
|
|
32
|
+
'com.whyshu.daily-report-timer': { desc: '日报(每小时直跑脚本)', kind: 'report', statusFile: 'daily-report-timer-status.json' },
|
|
33
|
+
'com.whyshu.ml-listing-timer': { desc: 'Listing 体检 + 推 ERP', kind: 'insight', statusFile: 'ml-insight-listing-status.json' },
|
|
34
|
+
'com.whyshu.ml-market-timer': { desc: '竞品快照(只读)', kind: 'insight', statusFile: 'ml-insight-market-status.json' },
|
|
35
|
+
'com.whyshu.dsh-web': { desc: 'dsh web 宿主(按机器角色)', kind: 'host' },
|
|
36
|
+
'com.whyshu.argent-bridge': { desc: '飞书桥(按机器角色)', kind: 'host' },
|
|
37
|
+
'com.whyshu.fulfillment-poll': { desc: '旧轮询(已退役,应清理)', kind: 'retired' },
|
|
38
|
+
// 2026-11-27:客户机实测清单里出现但我们漏收录的(截图里显示"未知"的正是这些)
|
|
39
|
+
'com.whyshu.ml-insight-timer': { desc: '店铺诊断(每小时 :20 跟随日报快照)', kind: 'insight', statusFile: 'ml-insight-diagnose-status.json' },
|
|
40
|
+
'com.whyshu.ziniao-keepalive': { desc: '紫鸟浏览器保活(每 3 分钟)', kind: 'host' },
|
|
41
|
+
'com.whyshu.caffeinate': { desc: '防休眠(常驻)', kind: 'host' },
|
|
42
|
+
'com.whyshu.xzh-browser': { desc: '鑫中航浏览器(常驻,旧流程遗留)', kind: 'host' },
|
|
43
|
+
'com.whyshu.argent-runner': { desc: '旧 argent runner(旧插件版,应退役)', kind: 'retired' },
|
|
44
|
+
'com.whyshu.argent-web': { desc: '旧 argent web(旧插件版,应退役)', kind: 'retired' },
|
|
45
|
+
'com.whyshu.dsh-portforward': { desc: 'dsh 端口转发(常驻,开发机用)', kind: 'host' },
|
|
46
|
+
'com.whyshu.dsh-release-watch': { desc: '发布监控(每日,开发/运维用)', kind: 'host' },
|
|
47
|
+
'com.whyshu.usage-anchor': { desc: '用量统计锚点(每日)', kind: 'host' },
|
|
48
|
+
'com.whyshu.billing-mode-check': { desc: '计费模式自检(每 3 小时)', kind: 'host' },
|
|
49
|
+
'com.whyshu.argent-ci': { desc: 'CI 任务(运维用)', kind: 'host' },
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
/** 前缀级退役/历史判定。 */
|
|
53
|
+
export function classifyLabel(label) {
|
|
54
|
+
const name = String(label || '')
|
|
55
|
+
const hit = KNOWN_LABELS[name]
|
|
56
|
+
if (hit) return { label: name, ...hit }
|
|
57
|
+
if (name.startsWith('com.whyshu.flow-trigger')) {
|
|
58
|
+
return { label: name, desc: '流程触发器(2026-10-29 起退役;新机不应有,残留应清理)', kind: 'retired' }
|
|
59
|
+
}
|
|
60
|
+
if (name.startsWith('com.whyshu.publish-')) return { label: name, desc: '发布任务(运维用,按时段)', kind: 'host' }
|
|
61
|
+
if (name.startsWith('com.whyshu.')) return { label: name, desc: '本机运维定时器(未收录用途;技术详情可见标签)', kind: 'unknown' }
|
|
62
|
+
return { label: name, desc: '非 whyshu 标签', kind: 'other' }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 纯函数:解析 `launchctl list` 输出(每行 `PID\tStatus\tLabel`)。
|
|
67
|
+
* @returns {Array<{label:string, pid:number|null, lastExit:number|null}>}
|
|
68
|
+
*/
|
|
69
|
+
export function parseLaunchctlList(text) {
|
|
70
|
+
const out = []
|
|
71
|
+
for (const line of String(text || '').split('\n')) {
|
|
72
|
+
const cols = line.trim().split(/\s+/)
|
|
73
|
+
if (cols.length < 3) continue
|
|
74
|
+
const [pidRaw, exitRaw, ...rest] = cols
|
|
75
|
+
const label = rest.join(' ')
|
|
76
|
+
if (!label.startsWith('com.whyshu.')) continue
|
|
77
|
+
const pid = pidRaw === '-' ? null : Number(pidRaw)
|
|
78
|
+
const lastExit = exitRaw === '-' ? null : Number(exitRaw)
|
|
79
|
+
out.push({ label, pid: Number.isFinite(pid) ? pid : null, lastExit: Number.isFinite(lastExit) ? lastExit : null })
|
|
80
|
+
}
|
|
81
|
+
return out
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 纯函数:从 plist XML 里读排程(支持 `StartCalendarInterval` 的 Hour/Minute 与 `StartInterval` 秒)。
|
|
86
|
+
* @returns {{type:'calendar',hour:number|null,minute:number}|{type:'interval',seconds:number}|null}
|
|
87
|
+
*/
|
|
88
|
+
export function parsePlistSchedule(xml) {
|
|
89
|
+
const s = String(xml || '')
|
|
90
|
+
const cal = s.match(/<key>StartCalendarInterval<\/key>[\s\S]*?<\/dict>/)
|
|
91
|
+
if (cal) {
|
|
92
|
+
const block = cal[0]
|
|
93
|
+
const hour = block.match(/<key>Hour<\/key>\s*<integer>(\d+)<\/integer>/)
|
|
94
|
+
const minute = block.match(/<key>Minute<\/key>\s*<integer>(\d+)<\/integer>/)
|
|
95
|
+
if (minute) return { type: 'calendar', hour: hour ? Number(hour[1]) : null, minute: Number(minute[1]) }
|
|
96
|
+
}
|
|
97
|
+
const interval = s.match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/)
|
|
98
|
+
if (interval) return { type: 'interval', seconds: Number(interval[1]) }
|
|
99
|
+
return null
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 纯函数:把三路事实合成清单。
|
|
104
|
+
* @param {{launchctlText?:string, plists?:Record<string,string>, statuses?:Record<string,object>}} p
|
|
105
|
+
*/
|
|
106
|
+
export function buildInventory({ launchctlText = '', plists = {}, statuses = {} } = {}) {
|
|
107
|
+
const loaded = parseLaunchctlList(launchctlText)
|
|
108
|
+
const byLabel = new Map()
|
|
109
|
+
for (const row of loaded) {
|
|
110
|
+
const c = classifyLabel(row.label)
|
|
111
|
+
const schedule = plists[row.label] ? parsePlistSchedule(plists[row.label]) : null
|
|
112
|
+
const status = c.statusFile ? statuses[c.statusFile] || null : null
|
|
113
|
+
byLabel.set(row.label, {
|
|
114
|
+
...c,
|
|
115
|
+
loaded: true,
|
|
116
|
+
pid: row.pid,
|
|
117
|
+
lastExit: row.lastExit,
|
|
118
|
+
plist: Boolean(plists[row.label]),
|
|
119
|
+
schedule,
|
|
120
|
+
lastRunAt: status?.lastRunAt || null,
|
|
121
|
+
lastFinishAt: status?.lastFinishAt || null,
|
|
122
|
+
nextDueAt: status?.nextDueAt || null,
|
|
123
|
+
lastError: status?.lastError || (row.lastExit && row.lastExit !== 0 ? `launchd lastExit=${row.lastExit}` : ''),
|
|
124
|
+
})
|
|
125
|
+
}
|
|
126
|
+
// 有 plist 但没加载(装了没 bootstrap / 被 bootout)也要可见 —— 这是"静默停摆"的常见形态
|
|
127
|
+
for (const [label, xml] of Object.entries(plists)) {
|
|
128
|
+
if (byLabel.has(label)) continue
|
|
129
|
+
const c = classifyLabel(label)
|
|
130
|
+
const status = c.statusFile ? statuses[c.statusFile] || null : null
|
|
131
|
+
byLabel.set(label, {
|
|
132
|
+
...c, loaded: false, pid: null, lastExit: null, plist: true,
|
|
133
|
+
schedule: parsePlistSchedule(xml),
|
|
134
|
+
lastRunAt: status?.lastRunAt || null, lastFinishAt: status?.lastFinishAt || null,
|
|
135
|
+
nextDueAt: status?.nextDueAt || null,
|
|
136
|
+
lastError: 'plist 在,但 launchd 未加载(装了没 bootstrap/被 bootout)',
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
const timers = [...byLabel.values()].sort((a, b) => {
|
|
140
|
+
const rank = { worker: 0, report: 1, insight: 2, host: 3, retired: 8, unknown: 9, other: 9 }
|
|
141
|
+
return (rank[a.kind] ?? 9) - (rank[b.kind] ?? 9) || a.label.localeCompare(b.label)
|
|
142
|
+
})
|
|
143
|
+
return {
|
|
144
|
+
count: timers.length,
|
|
145
|
+
loadedCount: timers.filter((t) => t.loaded).length,
|
|
146
|
+
retiredCount: timers.filter((t) => t.kind === 'retired').length,
|
|
147
|
+
missingCount: timers.filter((t) => !t.loaded).length,
|
|
148
|
+
timers,
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 取读文件的安全版(缺/坏 ⇒ null)。 */
|
|
153
|
+
function readMaybe(file) {
|
|
154
|
+
try { return readFileSync(file, 'utf8') } catch { return null }
|
|
155
|
+
}
|
|
156
|
+
function readJsonMaybe(file) {
|
|
157
|
+
const t = readMaybe(file)
|
|
158
|
+
if (!t) return null
|
|
159
|
+
try { const v = JSON.parse(t); return v && typeof v === 'object' ? v : null } catch { return null }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** 只读采集:launchctl + LaunchAgents plist + 状态文件。 */
|
|
163
|
+
export function collect({ launchctlFile = '', plistDir = '', dataDir = '' } = {}) {
|
|
164
|
+
const notes = []
|
|
165
|
+
let launchctlText = ''
|
|
166
|
+
if (launchctlFile) {
|
|
167
|
+
launchctlText = readMaybe(launchctlFile) || ''
|
|
168
|
+
if (!launchctlText) notes.push(`launchctl 文件读不到:${launchctlFile}`)
|
|
169
|
+
} else {
|
|
170
|
+
try {
|
|
171
|
+
launchctlText = execFileSync('launchctl', ['list'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
|
|
172
|
+
} catch (e) {
|
|
173
|
+
notes.push(`launchctl list 失败:${String((e && e.message) || e).slice(0, 200)}`)
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const dir = plistDir || join(homedir(), 'Library', 'LaunchAgents')
|
|
177
|
+
const plists = {}
|
|
178
|
+
try {
|
|
179
|
+
for (const f of readdirSync(dir)) {
|
|
180
|
+
if (!f.endsWith('.plist') || !f.startsWith('com.whyshu.')) continue
|
|
181
|
+
const xml = readMaybe(join(dir, f))
|
|
182
|
+
if (xml) plists[f.slice(0, -'.plist'.length)] = xml
|
|
183
|
+
}
|
|
184
|
+
} catch (e) {
|
|
185
|
+
notes.push(`plist 目录读不到:${dir}(${String((e && e.message) || e).slice(0, 120)})`)
|
|
186
|
+
}
|
|
187
|
+
const statuses = {}
|
|
188
|
+
for (const spec of Object.values(KNOWN_LABELS)) {
|
|
189
|
+
if (!spec.statusFile) continue
|
|
190
|
+
const v = readJsonMaybe(join(dataDir, spec.statusFile))
|
|
191
|
+
if (v) statuses[spec.statusFile] = v
|
|
192
|
+
}
|
|
193
|
+
const inv = buildInventory({ launchctlText, plists, statuses })
|
|
194
|
+
return { ok: notes.length === 0 || inv.count > 0, notes, ...inv }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const isDirect = (() => {
|
|
198
|
+
try { return import.meta.url === pathToFileURL(process.argv[1] || '').href } catch { return false }
|
|
199
|
+
})()
|
|
200
|
+
|
|
201
|
+
if (isDirect) {
|
|
202
|
+
const args = process.argv.slice(2)
|
|
203
|
+
const argVal = (n) => { const i = args.indexOf(n); return i >= 0 && args[i + 1] ? args[i + 1] : null }
|
|
204
|
+
const has = (n) => args.includes(n)
|
|
205
|
+
if (has('-h') || has('--help')) {
|
|
206
|
+
console.log(`系统定时器清单(只读)
|
|
207
|
+
|
|
208
|
+
用法: node scripts/argent-timers.mjs [选项]
|
|
209
|
+
--json 结构化输出(MCP / ERP 心跳复用)
|
|
210
|
+
--launchctl-file <p> 从文件读 launchctl list 输出(离线夹具)
|
|
211
|
+
--plist-dir <p> LaunchAgents 目录(默认 ~/Library/LaunchAgents)
|
|
212
|
+
--data-dir <p> 数据根(读状态文件,默认 argent 数据目录)
|
|
213
|
+
说明:只读;⛔ 不 bootstrap/bootout、不写文件。`)
|
|
214
|
+
process.exit(0)
|
|
215
|
+
}
|
|
216
|
+
const dataDir = argVal('--data-dir') || resolveDataDir({ env: process.env }).dir
|
|
217
|
+
const result = collect({ launchctlFile: argVal('--launchctl-file') || '', plistDir: argVal('--plist-dir') || '', dataDir })
|
|
218
|
+
if (has('--json')) { console.log(JSON.stringify(result, null, 2)); process.exit(result.ok ? 0 : 2) }
|
|
219
|
+
console.log(`系统定时器:${result.count} 条(已加载 ${result.loadedCount} / 未加载 ${result.missingCount} / 退役残留 ${result.retiredCount})`)
|
|
220
|
+
for (const t of result.timers) {
|
|
221
|
+
const sched = t.schedule ? (t.schedule.type === 'calendar' ? `${t.schedule.hour ?? '*'}:${String(t.schedule.minute).padStart(2, '0')}` : `每 ${t.schedule.seconds}s`) : '—'
|
|
222
|
+
const state = t.loaded ? '✅ 在跑' : '⚠️ 未加载'
|
|
223
|
+
console.log(` ${state} ${t.label}(${t.desc})排程=${sched}${t.lastRunAt ? ' · 上次=' + t.lastRunAt : ''}${t.lastError ? ' · ' + t.lastError : ''}`)
|
|
224
|
+
}
|
|
225
|
+
for (const n of result.notes) console.log(` ℹ ${n}`)
|
|
226
|
+
process.exit(result.ok ? 0 : 2)
|
|
227
|
+
}
|