dsh-git-push 2.8.4 → 2.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -468,6 +468,7 @@ dsh-git-push/
468
468
  │ ├── build-client.mjs — 客户端分片拼接(PART_ORDER + --check 门禁 + 形态铁律自检)
469
469
  │ ├── check.mjs — 语法检查脚本(npm run check)
470
470
  │ ├── clean-date-comments.py — (待注释)
471
+ │ ├── cpu-sample.mjs — (待注释)
471
472
  │ ├── doc-drift.mjs — (待注释)
472
473
  │ ├── doc-func.mjs — (待注释)
473
474
  │ ├── doc-tree.mjs — (待注释)
@@ -522,6 +523,7 @@ dsh-git-push/
522
523
  │ ├── test-audit-npm-publish-rules.mjs — (待注释)
523
524
  │ ├── test-audit-push-boundary.mjs — (待注释)
524
525
  │ ├── test-audit-scope.mjs — 审计作用域/凭据占位符回归测试
526
+ │ ├── test-audit-slot-order.mjs — (待注释)
525
527
  │ ├── test-audit.mjs — 审计总入口测试(auditFull/changed/豁免/gitignore)
526
528
  │ ├── test-auditignore.mjs — (待注释)
527
529
  │ ├── test-auto-push.mjs — 任务完成自动推送测试(检测纯函数 + registerAutoPush 门控监听注册)
@@ -564,6 +566,7 @@ dsh-git-push/
564
566
  │ ├── test-ext-variable-min-length.mjs — (待注释)
565
567
  │ ├── test-false-positive-fixes.mjs — 误报修复回归测试
566
568
  │ ├── test-file-health.mjs — 文件健康度矩阵评分测试
569
+ │ ├── test-filter-ext.mjs — (待注释)
567
570
  │ ├── test-folder-scope.mjs — 目录级审计作用域回归测试
568
571
  │ ├── test-func-doc-drift.mjs — (待注释)
569
572
  │ ├── test-generated-html-artifact.mjs — (待注释)
@@ -590,6 +593,7 @@ dsh-git-push/
590
593
  │ ├── test-module-splitter-multiline.mjs — (待注释)
591
594
  │ ├── test-module-splitter.mjs — module_splitter 工具 + CLI 接入测试(契约 + 行为 + 脚本随插件发布)
592
595
  │ ├── test-name-length-scope.mjs — (待注释)
596
+ │ ├── test-npm-enobufs.mjs — (待注释)
593
597
  │ ├── test-npm-install.mjs — (待注释)
594
598
  │ ├── test-npm-publish.mjs — (待注释)
595
599
  │ ├── test-npm-registry.mjs — (待注释)
@@ -104,7 +104,7 @@ export async function runAuditApi(repo, params = {}, cfg = {}) {
104
104
  scope,
105
105
  rulesetDir: params.rulesetDir || '',
106
106
  maxScanFiles: params.maxScanFiles ?? cfg.maxScanFiles ?? 0,
107
- slots: cfg.auditRuleOrder && cfg.auditRuleOrder.length ? cfg.auditRuleOrder : undefined,
107
+ slots: undefined, // auditRuleOrder 是「加载顺序」不是白名单 ✗(详见 lib/commit-push.js 注释;禁用槽位用 auditDisabledSlots ✓)
108
108
  disabledSlots: Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [],
109
109
  includeIgnored: params.includeIgnored === true,
110
110
  };
@@ -26,7 +26,11 @@ export const TOOL_REGISTRY = [
26
26
  name: 'git_commit_push', cli: 'commit', description: '一键提交并推送:一次调用 = 审计(blocker 拦截,可关)→ 有改动才 commit → 有可推内容才 push。零改动是**正常成功路径**:返回 ok:true + committed:false(job 状态 completed,不是失败);远端已最新则 ok:true + pushed:false;本地领先远端的已提交内容照样会推。message 必填(零改动时用不到);requirementsConfirmed=true(开发者要求全部核对达标)——**存在要求清单时任何调用都要带**(与有无改动、是否推送无关);push=false 只提交;dryRun 只模拟',
27
27
  params: [
28
28
  { flag: 'repo', type: 'string', positional: 0, required: true, desc: '仓库绝对路径' },
29
- { flag: 'message', type: 'string', schemaType: 'message', required: true, desc: 'commit message:可传字符串;或数组(元素为字符串,或 {what,type?,scope?,why?,verify?,refs?});或 {subject?,items:[...]}。仅 what 必填,type/scope/why/verify/refs 可空' },
29
+ { flag: 'message', type: 'string', required: true, desc: 'commit message(字符串,必填):可写整条提交信息;要传结构化多条目请用 messageItems(它会作为要点与正文)' },
30
+ // ⚠️ 数组/对象形态**必须走独立参数**:宿主在进插件之前先按工具 JSON schema 校验参数,
31
+ // 而它对 message 这类标量参数只认 type:'string'(实测 anyOf 与「类型数组」两种写法
32
+ // 都被读成 string ✗,报 invalid arguments: "message" must be a string ⇒ 非字符串根本到不了插件 ✓)
33
+ { flag: 'messageItems', type: 'array', desc: '结构化条目数组:元素为字符串,或 {what,type?,scope?,why?,verify?,refs?};仅 what 必填,type/scope/why/verify/refs 可空' },
30
34
  { flag: 'push', type: 'boolean', default: true, desc: '是否推送(默认 true)' },
31
35
  { flag: 'audit', type: 'boolean', desc: '提交前审计(默认取配置)' },
32
36
  { flag: 'dryRun', type: 'boolean', desc: 'dry-run 只模拟不写入' },
@@ -42,6 +42,7 @@ export const FUNCTION_USAGE_HINT = [
42
42
  '【凭据由插件托管,不要到处找凭据】GitHub token 与 SSH 公钥存放在插件 config.json(git-push/config.json 的 githubToken、sshPub 键,0600);SSH 私钥仍为文件(git-push/id_rsa),由插件的推送/校验流程自动读取与选择通道(默认 SSH,token 401 回退 SSH)。',
43
43
  '需要判断登录态 → 调 git_account_check;需要推送 → 调 git_commit_push。不要遍历用户目录找 token、不要把凭据抄进命令行或文档、不要在回复里明文输出凭据。',
44
44
  '【调用纪律】提交类操作先 git_scan 确认目标仓库;提交前核对 README(功能表/版本记录/用法);审计拦截 blocker 时先修复再提交;用户未要求推送时不要 push。',
45
+ '· message 参数:**只能传字符串**(宿主在进插件前按工具 schema 校验,只认标量类型——数组/对象会被直接拒 ✗);要写结构化多条目请用配套参数 `messageItems`(数组:元素为字符串,或 {what,type?,scope?,why?,verify?,refs?};仅 what 必填)——它作为要点与正文,message 则作标题 ✓',
45
46
  '(这些纪律只在**会产生新提交/要推送**时才起作用;工作区没改动时直接调用 git_commit_push 也不会报错——不要因为「没东西可提交」就绕开插件手敲 git。)',
46
47
  ].join('\n');
47
48
 
@@ -57,6 +57,7 @@ async function pushWithPostSteps(args, env, cfg) {
57
57
  const r = await commitAndPush({
58
58
  repoPath: args.repo,
59
59
  message: args.message,
60
+ messageItems: args.messageItems,
60
61
  push: args.push !== false,
61
62
  dryRun: args.dryRun === true,
62
63
  customIgnorePatterns: args.ignorePatterns || '',
@@ -120,6 +121,11 @@ export function pushJobOutcome(r = {}) {
120
121
  const why = res.error || (res.blocked ? '推送被拦截' : '未完成');
121
122
  return { status: 'failed', detail: res.blocked ? `未推送(被拦截):${why}` : `未完成:${why}` };
122
123
  }
124
+ // dry-run:**什么都没写** ⇒ 文案必须自证「模拟」,不能说「已提交」✗(实测回执曾误报「已提交,未推送」)
125
+ if (res.dryRun === true) {
126
+ const st = Array.isArray(res.steps) && res.steps.length ? `(步骤:${res.steps.join(' → ')})` : '';
127
+ return { status: 'completed', detail: `dry-run 模拟完成:**未提交、未推送**${st}` };
128
+ }
123
129
  const pushInfo = res.push || {};
124
130
  if (res.pushed === true) {
125
131
  if (pushInfo.verified === false) {
@@ -262,7 +268,11 @@ async function callNpmPublishJob(args = {}, jobs, exec, log, env = {}, cfg = {})
262
268
  confirm: args.confirm === true,
263
269
  });
264
270
  const outcome = (r) => (r && r.ok
265
- ? { status: 'done', output: JSON.stringify(r) }
271
+ // 完成态必须用宿主认可的枚举值:`completed`(不是 `done` ✗)——
272
+ // 历史缺陷:这里写 `status:'done'`,宿主 job_output 的校验只认
273
+ // running|stopping|completed|killed|failed ⇒ 已完成的 job 一律读不出(报
274
+ // `"value.job.status" must be one of [...]`),表现为「等了很久,结果似乎没成功」✗。
275
+ ? { status: 'completed', output: JSON.stringify(r) }
266
276
  : { status: 'failed', detail: String((r && (r.error || r.blocked)) || 'npm publish 失败'), output: JSON.stringify(r || {}) });
267
277
  if (!jobs || typeof jobs.start !== 'function') {
268
278
  const r = await doPublish();
@@ -327,7 +337,7 @@ async function callCommitPush(args, env, cfg, log, jobs, exec) {
327
337
  audit: args.audit,
328
338
  // 不再透传 auditLevel——审计固定走完整流程(正则初筛 + AST 语义检查)
329
339
  rulesetDir: args.ruleset,
330
- slots: cfg.auditRuleOrder && cfg.auditRuleOrder.length ? cfg.auditRuleOrder : undefined,
340
+ slots: undefined, // auditRuleOrder 是「加载顺序」不是白名单 ✗(详见 lib/commit-push.js 注释;禁用槽位用 auditDisabledSlots ✓)
331
341
  cfg,
332
342
  });
333
343
  if (!auditGate.ok) return auditGate; // { ok:false, blocked:true, audit }
@@ -374,7 +384,7 @@ function buildAuditOpts(args, cfg, scope) {
374
384
  scope,
375
385
  rulesetDir: args.ruleset || '',
376
386
  maxScanFiles: cfg.maxScanFiles,
377
- slots: cfg.auditRuleOrder && cfg.auditRuleOrder.length ? cfg.auditRuleOrder : undefined,
387
+ slots: undefined, // auditRuleOrder 是「加载顺序」不是白名单 ✗(详见 lib/commit-push.js 注释;禁用槽位用 auditDisabledSlots ✓)
378
388
  disabledSlots: Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [],
379
389
  includeIgnored: args.includeIgnored === true,
380
390
  // 分析覆盖率信息项(默认开;coverage:false 关闭——大仓库省一次读取+解析)
package/lib/app/tools.js CHANGED
@@ -12,17 +12,11 @@ import { TOOL_REGISTRY } from './command-registry.js';
12
12
  function paramsToParameters(params = []) {
13
13
  const out = {};
14
14
  for (const p of params) {
15
- // 参数类型 → JSON schema:boolean 直通;schemaType='message' 的(message 参数)额外接受
16
- // 数组与对象形态(元素为字符串或结构化条目),以支持「传数组」的新用法 ✓
17
- if (p.schemaType === 'message') {
18
- out[p.flag] = {
19
- anyOf: [
20
- { type: 'string' },
21
- { type: 'array', items: { anyOf: [{ type: 'string' }, { type: 'object' }] } },
22
- { type: 'object' },
23
- ],
24
- description: p.desc || '',
25
- };
15
+ // 参数类型 → JSON schema:**只产出宿主认的标量类型**(boolean / string / array)——
16
+ // 实测宿主校验不认 anyOf、也不认 JSON Schema 的「类型数组」写法(都按 string 处理 ✗,
17
+ // 报 invalid arguments: "x" must be a string)⇒ 复杂形态一律拆成独立参数 ✓
18
+ if (p.type === 'array') {
19
+ out[p.flag] = { type: 'array', description: p.desc || '' };
26
20
  } else {
27
21
  out[p.flag] = { type: p.type === 'boolean' ? 'boolean' : 'string', description: p.desc || '' };
28
22
  }
@@ -11,6 +11,11 @@ metadata:
11
11
  rules:
12
12
  # ── 内存爆炸检测(文档 §13 示例规则落地:子模式 + per-pattern message)──
13
13
  - id: performance/memory-bomb
14
+ # astConfirm: 正则只做初筛,命中行必须再经 token 级确认「真在代码里」——
15
+ # 已消除**注释行**里的示例文本误报(如讲解「while(true) 占死线程」的注释 ✗)。
16
+ # 已知边界:匹配落在**字符串字面量内**时仍会报(makeCodeLineFilter 是行级判定,
17
+ # 看不到列号位置)——实测影响面仅第三方插件测试脚本 1 处,评估后**不修** ✓
18
+ astConfirm: true
14
19
  name: "检测可能导致内存爆炸的代码"
15
20
  category: "performance"
16
21
  severity: "warning"
@@ -135,6 +140,9 @@ rules:
135
140
 
136
141
  # ── 无界循环 / 高 CPU 轮询(性能补充)──
137
142
  - id: performance/busy-wait-loop
143
+ # 同上:注释里的 while(true) 已不再误报 ✓;
144
+ # 字符串字面量里的 'while (true) {}'(测试用)仍会报 —— 已知边界、评估后不修 ✓
145
+ astConfirm: true
138
146
  name: "忙等待循环(高 CPU 空转)"
139
147
  category: "performance"
140
148
  severity: "warning"
@@ -30,7 +30,13 @@
30
30
  * @returns {object} 过滤后的 grouped(规则数组已按 exts 裁剪)
31
31
  */
32
32
  export function filterRulesByExt(grouped, relPath) {
33
- const ext = String(relPath || '').split('.').pop().toLowerCase();
33
+ // 取扩展名必须**先取 basename 再取最后一个点之后**:
34
+ // 旧实现 String(relPath).split('.').pop() 对含点目录的路径会取错 ✗ ——
35
+ // 例:docs/.vitepress/theme/index.ts ⇒ 得到 "vitepress/theme/index"(不是 ts)
36
+ // ⇒ 该文件所有声明了 exts 的规则**全部匹配不上**(审计实测:.vitepress 下文件只拿到通用规则)。
37
+ // 另:无扩展名文件(Makefile 等)返回空串,声明 exts 的规则自然不匹配(正确语义)。
38
+ const base = String(relPath || '').replace(/\\/g, '/').split('/').pop() || '';
39
+ const ext = base.includes('.') ? base.split('.').pop().toLowerCase() : '';
34
40
  const out = {};
35
41
  for (const [kind, rules] of Object.entries(grouped || {})) {
36
42
  if (!Array.isArray(rules)) { out[kind] = rules; continue; }
@@ -34,9 +34,13 @@ export async function runAudit({ repoPath = '', audit, rulesetDir, slots, cfg: e
34
34
  const cfg = extCfg || defaultConfig();
35
35
  const doAudit = audit ?? cfg.auditEnabled;
36
36
  if (!doAudit) return { ok: true, audit: null };
37
- const slotOrder = Array.isArray(slots) && slots.length ? slots
38
- : Array.isArray(cfg.auditRuleOrder) && cfg.auditRuleOrder.length ? cfg.auditRuleOrder
39
- : undefined;
37
+ // ⚠️ auditRuleOrder 的语义是「槽位**加载顺序**」(见 schema 描述),**不是白名单** ✗。
38
+ // 历史缺陷:这里把它当 slots 传下去,而 loadRuleFiles 把 slots 当「只加载列出的包」用,
39
+ // 于是清单外的规则包(python/cpp/go/java/php/rust/swift/template…)被**静默丢弃** ✗——
40
+ // 实测:一个 105 个 .py 的项目上 7 条 python/* 规则零命中、连 python 槽位都不存在;
41
+ // 把该字段置空后同一项目 60 条 → 197 条、python/* 命中 0 → 5 ✓。
42
+ // 现在只保留显式传入的 slots(API/工具级白名单);配置里的顺序不再当白名单(禁用请用 auditDisabledSlots ✓)。
43
+ const slotOrder = Array.isArray(slots) && slots.length ? slots : undefined;
40
44
  const auditRes = await auditWithScope(repoPath || '.', {
41
45
  scope: cfg.auditScanScope || 'diff',
42
46
  maxScanFiles: cfg.maxScanFiles,
@@ -62,7 +66,7 @@ export async function runAudit({ repoPath = '', audit, rulesetDir, slots, cfg: e
62
66
  // 修复背景:私有库被拦的回归——
63
67
  // 此前拦截判定只看「示例目录」、没有可见性分级,
64
68
  // comment / docs / security 等槽位规则不受 private 槽位(凭据 glob)约束,私有留痕仓库被拦。
65
- // 承诺原文:「私密文件与工作留痕(会话记录/凭据/留痕)在私有仓库可正常提交推送,
69
+ // 承诺原文:「私密文件与工作留痕(留痕记录/凭据/笔记)在私有仓库可正常提交推送,
66
70
  // 不需要额外豁免标记」。此前拦截判定只看「示例目录」、没有任何可见性分级,而
67
71
  // conv-*/docs/security 等槽位规则不受 private 槽位(凭据 glob)的可见性分级约束 →
68
72
  // 私有留痕仓库被上百条 conv-* blocker 拦下(实测回归:ai-work-archive 192 条)。
package/lib/git/push.js CHANGED
@@ -54,13 +54,19 @@ import { resolveRepoVisibility } from './visibility.js';
54
54
  * customIgnorePatterns:逗号/换行分隔的 gitignore pattern,追加进 .gitignore(幂等)
55
55
  * @returns {{ok, steps: string[], commitSha?, pushed?, push?, remoteHeads?, error?}}
56
56
  */
57
- export async function commitAndPush({ repoPath = '', message = '', push = true, dryRun = false, token = '', customIgnorePatterns = '', requirementsConfirmed = false, force = false, pushMethod = 'ssh', pushGate = false, pushConfirmed = false, paths = '' } = {}) {
57
+ export async function commitAndPush({ repoPath = '', message = '', messageItems = null, push = true, dryRun = false, token = '', customIgnorePatterns = '', requirementsConfirmed = false, force = false, pushMethod = 'ssh', pushGate = false, pushConfirmed = false, paths = '' } = {}) {
58
58
  const steps = [];
59
59
  if (!repoPath || !existsSync(join(repoPath, '.git'))) return { ok: false, steps: ['预检'], error: `非 git 仓库: ${repoPath || '(空)'}` };
60
60
  // message 支持三种形态(字符串 / 数组 / {subject,items}):在预检处**单点**组装成规范提交信息,
61
61
  // 后续流程(add / commit -m / 回执)只用 built.message —— 避免多处各自解析导致行为分叉。
62
62
  // 字符串形态原样透传(既有调用方行为不变);数组/对象形态由 lib/git/commit-message.js 组装。
63
- const built = buildCommitMessage(message);
63
+ // message(字符串)与 messageItems(数组)合并:字符串作**标题**、数组作要点与正文 ✓
64
+ // 为什么数组不走 message 本身:宿主在进插件前按工具 schema 校验参数,而它只认标量类型
65
+ // (anyOf / 类型数组都被读成 string ✗)⇒ 非字符串根本到不了插件 ✓(见 command-registry 注释)
66
+ const msgInput = Array.isArray(messageItems) && messageItems.length
67
+ ? { subject: String(message || '').trim(), items: messageItems }
68
+ : message;
69
+ const built = buildCommitMessage(msgInput);
64
70
  if (!built.ok) return { ok: false, steps: ['预检'], error: built.error };
65
71
  const commitMessage = built.message;
66
72
  // D13 开发者要求门禁(commitPushPreflight 语义):要求清单存在且未核对 → 拦截。
@@ -121,7 +127,7 @@ export async function commitAndPush({ repoPath = '', message = '', push = true,
121
127
  const gi = privateExempt
122
128
  ? { added: 0, files: (await scanSensitiveFiles(repoPath)).map((h) => h.path), baseline: 0, custom: 0, tracked: [], unstaged: [], skipped: 'private-repo-exempt' }
123
129
  : await ensureGitignore(repoPath, { customIgnorePatterns });
124
- // 敏感文件只报告不动作(用户指令:扫描到不改动 git 忽略,由仓库方自行处理)
130
+ // 敏感文件只报告不动作(既定行为:扫描到不改动 git 忽略,由仓库方自行处理)
125
131
  if (gi.files.length) steps.push(`sensitive-scan(${gi.files.length}文件, 只报告)`);
126
132
  else if (gi?.added > 0) steps.push(`.gitignore(+${gi.added}条)`);
127
133
  if (privateExempt) steps.push(`private-exempt(${visReason})`);
@@ -72,7 +72,9 @@ export function packDryRun({ dir, registry = DEFAULT_REGISTRY, workspaceRoot = '
72
72
  const merged = { ...process.env };
73
73
  const rc = writeNpmrc({ workspaceRoot, registry, token });
74
74
  if (!rc.ok) return { ok: false, error: rc.error || 'npmrc 写入失败' };
75
- const r = runNpm(['pack', '--dry-run', '--json', ...npmArgs({ npmrcFile: rc.file, registry })], { timeoutMs, env: merged });
75
+ // cwd 必须显式给:npm pack 以「工作目录」为目标包,继承宿主 cwd 会去错目录
76
+ // (实测:宿主 cwd 无 package.json ⇒ ENOENT;有 ⇒ 打包整棵树 ⇒ ENOBUFS)
77
+ const r = runNpm(['pack', '--dry-run', '--json', ...npmArgs({ npmrcFile: rc.file, registry })], { timeoutMs, env: merged, cwd: dir });
76
78
  if (!r.ok) return { ok: false, error: r.error || 'npm pack --dry-run 失败', stdout: r.stdout };
77
79
  let info = null;
78
80
  try {
@@ -142,7 +144,9 @@ export async function publishPackage({
142
144
  if (otp) args.push('--otp', String(otp));
143
145
 
144
146
  const logPath = appendPublishLog(`publish START dryRun=${dryRun} ${info.name}@${info.version} tag=${tg} files=${pack.files.length}`, { workspaceRoot });
145
- const r = runNpm(args, { timeoutMs, env: { NO_UPDATE_NOTIFIER: '1' } });
147
+ // 同 pack:npm publish 也以「工作目录」为目标包,必须显式指向 info.dir,
148
+ // 否则会去发布宿主 cwd 下的包(或不存在的包)—— 这是发包类操作里最危险的一种错。
149
+ const r = runNpm(args, { timeoutMs, env: { NO_UPDATE_NOTIFIER: '1' }, cwd: info.dir });
146
150
  appendPublishLog(`publish END dryRun=${dryRun} ok=${r.ok} code=${r.code} err=${String(r.error || '').slice(0, 200)}`, { workspaceRoot });
147
151
  return {
148
152
  ok: !!r.ok,
@@ -53,11 +53,25 @@ export function resolveNpmBin({ env = process.env } = {}) {
53
53
  return 'npm';
54
54
  }
55
55
 
56
+ /**
57
+ * npm 子进程输出上限。默认 1MB 对大项目的 pack 清单偏小 —— 实测撞过 ENOBUFS。
58
+ */
59
+ const NPM_MAX_BUFFER = 16 * 1024 * 1024;
60
+ // ENOBUFS 重试上限:npm 在大依赖树上(npm ls / npm view 等)输出可能超过 16MB,
61
+ // 一旦超限 spawnSync 直接以 ENOBUFS 失败——对调用方表现为「npm 调用失败」,无法自解。
62
+ // 故首次超限后**放大缓冲重试一次**,仍失败才如实报错(并把「输出过大」这个真因写进文案)。
63
+ const NPM_MAX_BUFFER_LARGE = 128 * 1024 * 1024;
64
+
56
65
  /**
57
66
  * 跑一次 npm(短超时,收 stdout/stderr;不抛错)。
67
+ * @param {string[]} args npm 参数
68
+ * @param {{timeoutMs?:number, env?:object, cwd?:string}} [opts]
69
+ * cwd:**必须在目标包目录里跑的调用要显式传**(`npm pack` / `npm publish` 都以 cwd 为目标包)。
70
+ * 不传就继承宿主进程的工作目录 —— 实测后果是 npm 去错目录找 package.json:
71
+ * 该目录没有 package.json ⇒ ENOENT;有 ⇒ 去 pack 那整棵树 ⇒ 输出撑爆缓冲区 ⇒ ENOBUFS。
58
72
  * @returns {{ok:boolean, code:number, stdout?:string, stderr?:string, error?:string}}
59
73
  */
60
- export function runNpm(args = [], { timeoutMs = NPM_TIMEOUT_MS, env = {} } = {}) {
74
+ export function runNpm(args = [], { timeoutMs = NPM_TIMEOUT_MS, env = {}, cwd = '', maxBuffer } = {}) {
61
75
  const merged = { ...process.env, ...env };
62
76
  // 关键:npm 的入口是 `#!/usr/bin/env node` 脚本 ⇒ 子进程 PATH 里必须有 node,
63
77
  // 否则即使找到 npm 也会报「env: 'node': No such file or directory」(最小 PATH 宿主实测)。
@@ -65,7 +79,14 @@ export function runNpm(args = [], { timeoutMs = NPM_TIMEOUT_MS, env = {} } = {})
65
79
  const nodeDir = dirname(String(process.execPath || ''));
66
80
  if (nodeDir) merged.PATH = `${nodeDir}${delimiter}${merged.PATH || ''}`;
67
81
  const bin = resolveNpmBin({ env: merged });
68
- const r = spawnSync(bin, args, { encoding: 'utf8', timeout: timeoutMs, env: merged });
82
+ // maxBuffer 可注入:默认 16MB;测试传极小值(如 1)即可**确定性触发** ENOBUFS 走重试分支 ✓
83
+ const runNpmBuf = (buf) => spawnSync(bin, args, {
84
+ encoding: 'utf8', timeout: timeoutMs, env: merged, maxBuffer: buf,
85
+ ...(cwd ? { cwd } : {}),
86
+ });
87
+ const first = Number.isFinite(maxBuffer) && maxBuffer > 0 ? maxBuffer : NPM_MAX_BUFFER;
88
+ let r = runNpmBuf(first);
89
+ if (r.error && r.error.code === 'ENOBUFS') r = runNpmBuf(NPM_MAX_BUFFER_LARGE);
69
90
  if (r.error) {
70
91
  const timedOut = r.error.code === 'ETIMEDOUT';
71
92
  return { ok: false, code: -1, bin, error: timedOut ? `npm 超时(${timeoutMs}ms)` : `npm 调用失败(${bin}):${String(r.error.message || r.error)}` };
package/lib/self/index.js CHANGED
@@ -9,7 +9,10 @@
9
9
  */
10
10
 
11
11
 
12
- export const VERSION = '2.8.4'; // 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
12
+ export const VERSION = '2.8.6'; // 2.8.5:修 runNpm 不传 cwd —— npm pack/publish 会跑在**宿主进程的 cwd**(本机是 DSH 安装目录 /volume1/@appstore/DeepSeekHarness-NAS)而不是目标包目录。
13
+ // 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
14
+ // 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
15
+ // 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
13
16
  // 不再判「推送未落地」,改为如实标「推送已完成但未核验」(只有 404 才算远端真的没有该分支)。
14
17
  // 2.6.2:克隆「已存在且不完整」时可续传/重来——预览端点回报 partial(有进行中标记且无有效提交),
15
18
  // 前端预览框在不完整时给出「重来」(只清 .dsh-parts 分片、不动已下文件与用户内容);忙碌键前缀(clone:/vis:/push:)统一到单一出处。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-git-push",
3
- "version": "2.8.4",
3
+ "version": "2.8.6",
4
4
 
5
5
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
6
6
  "type": "module",
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CPU 现场采样器(独立脚本,按需启动;零依赖、只读 /proc)。
4
+ *
5
+ * 用途:CPU 异常(如经常 50%+)时**现场**抓证据——事后采样复现不出来,
6
+ * 必须在「异常正在发生」的那一刻记录:哪个进程、什么命令行、系统总占用、
7
+ * 是否 chrome/headless 在跑、宿主进程内存等。
8
+ *
9
+ * 为什么不做成插件常驻任务:30s 常驻采样虽便宜,但平时没人看,反而多一份常驻逻辑;
10
+ * 按需启动最省事,也不给宿主添负担。
11
+ *
12
+ * 用法:
13
+ * node scripts/cpu-sample.mjs # 默认 120 秒、每 5 秒一次
14
+ * node scripts/cpu-sample.mjs --seconds 300 --interval 2 --top 8
15
+ * node scripts/cpu-sample.mjs --out /tmp/cpu.jsonl --high 40
16
+ *
17
+ * 输出:① 控制台一行一样本(系统% + Top 进程)② JSONL 明细(每样本一行,含命令行)
18
+ * ③ 结束打印汇总(峰值、Top 常客、chrome 出现次数)与 JSONL 路径。
19
+ *
20
+ * 判定口径:进程 CPU% = 该进程 tick 增量 / 全机 tick 增量 × 100(= 占整机百分比,
21
+ * 与 top 的聚合口径一致);系统% = 1 - idle 增量/总增量。
22
+ */
23
+ import { readdirSync, readFileSync, appendFileSync, existsSync } from 'node:fs';
24
+ import { cpus, loadavg, hostname } from 'node:os';
25
+ import { join } from 'node:path';
26
+
27
+ const argv = process.argv.slice(2);
28
+ const arg = (name, dflt) => {
29
+ const i = argv.indexOf(`--${name}`);
30
+ return i >= 0 && argv[i + 1] !== undefined ? argv[i + 1] : dflt;
31
+ };
32
+ const SECONDS = Math.max(5, Number(arg('seconds', 120)) || 120);
33
+ const INTERVAL = Math.max(1, Number(arg('interval', 5)) || 5);
34
+ const TOP = Math.max(3, Number(arg('top', 6)) || 6);
35
+ const HIGH = Number(arg('high', 40)) || 40;
36
+ const OUT = String(arg('out', '') || '') || `/tmp/cpu-sample-${new Date().toISOString().replace(/[:.]/g, '-')}.jsonl`;
37
+ const NCPU = cpus().length || 1;
38
+
39
+ /** 读 /proc/stat 的 cpu 汇总行 → { total, idle }(单位:tick)。 */
40
+ function cpuTotals() {
41
+ try {
42
+ const line = readFileSync('/proc/stat', 'utf8').split('\n')[0] || '';
43
+ const f = line.trim().split(/\s+/).slice(1).map(Number);
44
+ const total = f.reduce((a, b) => a + (Number.isFinite(b) ? b : 0), 0);
45
+ const idle = (f[3] || 0) + (f[4] || 0); // idle + iowait
46
+ return { total, idle };
47
+ } catch { return { total: 0, idle: 0 }; }
48
+ }
49
+
50
+ /** 读某进程累计 CPU tick(utime+stime)。comm 可能含空格/括号 ⇒ 取最后一个 ')' 之后解析。 */
51
+ function procTicks(pid) {
52
+ try {
53
+ const s = readFileSync(`/proc/${pid}/stat`, 'utf8');
54
+ const rest = s.slice(s.lastIndexOf(')') + 2).trim().split(/\s+/);
55
+ // rest[0] = state ⇒ utime 是第 12 个字段(1-based 14)⇒ rest 下标 11、12
56
+ return (Number(rest[11]) || 0) + (Number(rest[12]) || 0);
57
+ } catch { return null; }
58
+ }
59
+
60
+ /** 某进程常驻内存 MB(statm 第 2 项 = resident pages)。 */
61
+ function procRssMB(pid) {
62
+ try {
63
+ const f = readFileSync(`/proc/${pid}/statm`, 'utf8').trim().split(/\s+/);
64
+ return Math.round(((Number(f[1]) || 0) * 4096) / 1048576);
65
+ } catch { return 0; }
66
+ }
67
+
68
+ /** 进程名与命令行(cmdline 为 NUL 分隔;截断到 160 字符)。 */
69
+ function procInfo(pid) {
70
+ let comm = '';
71
+ let cmd = '';
72
+ try { comm = readFileSync(`/proc/${pid}/comm`, 'utf8').trim(); } catch { /* 进程可能已退出 */ }
73
+ try { cmd = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').filter(Boolean).join(' '); } catch { /* 同上 */ }
74
+ return { comm, cmd: cmd.slice(0, 160) };
75
+ }
76
+
77
+ /** 枚举 /proc 下的数字目录(= 进程)。 */
78
+ function pids() {
79
+ try { return readdirSync('/proc').filter((n) => /^\d+$/.test(n)); } catch { return []; }
80
+ }
81
+
82
+ /** 内存概况(MB)。 */
83
+ function memMB() {
84
+ try {
85
+ const t = readFileSync('/proc/meminfo', 'utf8');
86
+ const get = (k) => Number((t.match(new RegExp(`^${k}:\\s+(\\d+) kB`, 'm')) || [])[1] || 0) / 1024;
87
+ return { total: Math.round(get('MemTotal')), available: Math.round(get('MemAvailable')) };
88
+ } catch { return { total: 0, available: 0 }; }
89
+ }
90
+
91
+ let prev = null; // { t: {total,idle}, pids: Map<pid, ticks> }
92
+ let hostPid = null;
93
+ const samples = [];
94
+
95
+ function detectHostPid() {
96
+ for (const p of pids()) {
97
+ const { cmd } = procInfo(p);
98
+ if (cmd.includes('packages/DeepSeekHarness-NAS/target/bin/node')) return Number(p);
99
+ }
100
+ return null;
101
+ }
102
+
103
+ /** 采一次样并返回记录(纯读,不抛错)。 */
104
+ function sampleOnce() {
105
+ const now = cpuTotals();
106
+ const cur = new Map();
107
+ for (const p of pids()) {
108
+ const t = procTicks(p);
109
+ if (t !== null) cur.set(p, t);
110
+ }
111
+ const rec = {
112
+ t: new Date().toISOString(),
113
+ ncpu: NCPU,
114
+ systemPct: null,
115
+ load: loadavg().map((x) => Number(x.toFixed(2))),
116
+ mem: memMB(),
117
+ host: null,
118
+ chrome: 0,
119
+ browsersvc: 0,
120
+ top: [],
121
+ };
122
+ if (prev && now.total > prev.t.total) {
123
+ const dTot = now.total - prev.t.total;
124
+ const dIdle = now.idle - prev.t.idle;
125
+ rec.systemPct = Number((100 * (1 - dIdle / dTot)).toFixed(1));
126
+ const list = [];
127
+ for (const [pid, ticks] of cur) {
128
+ const old = prev.pids.get(pid);
129
+ if (old === undefined) continue; // 新进程首个样本跳过(无基线)
130
+ const d = ticks - old;
131
+ if (d <= 0) continue;
132
+ const pct = Number(((100 * d) / dTot).toFixed(1));
133
+ if (pct < 0.2) continue;
134
+ const info = procInfo(pid);
135
+ list.push({ pid: Number(pid), pct, rssMB: procRssMB(pid), ...info });
136
+ }
137
+ list.sort((a, b) => b.pct - a.pct);
138
+ rec.top = list.slice(0, TOP);
139
+ rec.chrome = list.filter((x) => /chrome|headless/i.test(x.comm)).length;
140
+ rec.browsersvc = list.filter((x) => /browsersvc/i.test(x.cmd) && !/cpu-sample/.test(x.cmd)).length;
141
+ if (hostPid === null) hostPid = detectHostPid();
142
+ const h = hostPid ? list.find((x) => x.pid === hostPid) : null;
143
+ rec.host = h ? { pid: h.pid, pct: h.pct, rssMB: h.rssMB } : (hostPid ? { pid: hostPid, pct: 0, rssMB: procRssMB(hostPid) } : null);
144
+ }
145
+ prev = { t: now, pids: cur };
146
+ return rec;
147
+ }
148
+
149
+ function line(rec) {
150
+ const hi = rec.systemPct !== null && rec.systemPct >= HIGH;
151
+ const head = `${rec.t.slice(11, 19)} 系统 ${rec.systemPct === null ? '--' : `${rec.systemPct}%`} load ${rec.load[0]} mem ${rec.mem.available}/${rec.mem.total}MB chrome ${rec.chrome} browsersvc ${rec.browsersvc}`;
152
+ const tops = rec.top.slice(0, 4).map((x) => `${x.comm}:${x.pct}%`).join(' ');
153
+ return `${hi ? '⚠️ 高占用 ' : ' '}${head}${tops ? ` | ${tops}` : ''}`;
154
+ }
155
+
156
+ // ── 主流程 ──
157
+ console.log(`CPU 现场采样器 · 主机 ${hostname()} · ${NCPU} 核 · 每 ${INTERVAL}s 一次 · 共 ${SECONDS}s · 高占用阈值 ${HIGH}%`);
158
+ console.log(`输出 JSONL:${OUT}`);
159
+ sampleOnce(); // 建立基线(首样本无百分比)
160
+ let n = 0;
161
+ const timer = setInterval(() => {
162
+ const rec = sampleOnce();
163
+ n += 1;
164
+ samples.push(rec);
165
+ console.log(line(rec));
166
+ try { appendFileSync(OUT, `${JSON.stringify(rec)}\n`); } catch { /* 写失败不影响采样 */ }
167
+ if (n * INTERVAL >= SECONDS) finish();
168
+ }, INTERVAL * 1000);
169
+
170
+ function finish() {
171
+ clearInterval(timer);
172
+ const withPct = samples.filter((s) => s.systemPct !== null);
173
+ const peak = withPct.reduce((m, s) => Math.max(m, s.systemPct), 0);
174
+ const counter = new Map();
175
+ for (const s of withPct) for (const x of s.top) counter.set(x.comm, (counter.get(x.comm) || 0) + x.pct);
176
+ const regulars = [...counter.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6)
177
+ .map(([c, v]) => `${c}(${Math.round(v)}%)`);
178
+ const chromeHits = withPct.filter((s) => s.chrome > 0).length;
179
+ console.log('\n── 汇总 ──');
180
+ console.log(`样本数 ${withPct.length} · 系统峰值 ${peak}% · 平均 ${withPct.length ? (withPct.reduce((a, s) => a + s.systemPct, 0) / withPct.length).toFixed(1) : 0}%`);
181
+ console.log(`chrome/headless 出现样本数:${chromeHits}/${withPct.length}`);
182
+ console.log(`Top 常客(按累计 %):${regulars.join(' · ') || '(无)'}`);
183
+ console.log(`明细:${OUT}`);
184
+ process.exit(0);
185
+ }
186
+
187
+ // Ctrl-C 也能出汇总
188
+ process.on('SIGINT', finish);