shipgate-cli 0.0.0-stage → 0.2.2

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 (123) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +261 -2
  3. package/agents/context-builder.md +158 -0
  4. package/agents/debug-executor.md +234 -0
  5. package/assets/gates/classifier.js +245 -0
  6. package/assets/gates/dsh/index.js +767 -0
  7. package/assets/gates/dsh/policy.json +93 -0
  8. package/assets/gates/index.js +3 -0
  9. package/assets/gates/pi/index.js +1131 -0
  10. package/assets/gates/pi/policy.json +93 -0
  11. package/assets/gates/policy.js +4267 -0
  12. package/assets/gates/profiles/ai4s-dry-lab.json +64 -0
  13. package/assets/gates/profiles/ai4s-quant.json +36 -0
  14. package/assets/pi-extensions/auto-continue.ts +176 -0
  15. package/assets/pi-extensions/goal-mode.ts +313 -0
  16. package/bin/shipgate.mjs +9 -0
  17. package/commands/ai-spec.md +9 -0
  18. package/commands/api-first.md +33 -0
  19. package/commands/code-review.md +7 -0
  20. package/commands/codebase-context.md +19 -0
  21. package/commands/debug-ui.md +147 -0
  22. package/commands/debug.md +101 -0
  23. package/commands/dev-env-scan.md +18 -0
  24. package/commands/dev-host-init.md +28 -0
  25. package/commands/discover-skill-opportunities.md +33 -0
  26. package/commands/fork-sync.md +17 -0
  27. package/commands/gh-actions.md +26 -0
  28. package/commands/goal-driven-development.md +7 -0
  29. package/commands/intent-grill.md +7 -0
  30. package/commands/iteration-manager.md +7 -0
  31. package/commands/loop-engineer.md +21 -0
  32. package/commands/nodejs-npm-auto-release.md +12 -0
  33. package/commands/prd.md +7 -0
  34. package/commands/project-health-audit.md +7 -0
  35. package/commands/ralph-yolo.md +346 -0
  36. package/commands/ralph.md +226 -0
  37. package/commands/security-audit.md +7 -0
  38. package/commands/ux-experience-audit.md +133 -0
  39. package/docs/ARCHITECTURE.md +63 -0
  40. package/docs/GATES.md +106 -0
  41. package/docs/HARNESS.md +257 -0
  42. package/package.json +48 -4
  43. package/references/ADR-FORMAT.md +67 -0
  44. package/references/CONTEXT-FORMAT.md +62 -0
  45. package/references/mcp-config-template.json +54 -0
  46. package/scripts/fix-skill-frontmatter.mjs +66 -0
  47. package/scripts/migrate-skillpack.mjs +257 -0
  48. package/skills/ai-spec/SKILL.md +90 -0
  49. package/skills/api-first-modular/SKILL.md +411 -0
  50. package/skills/code-debugger/SKILL.md +379 -0
  51. package/skills/code-review/SKILL.md +62 -0
  52. package/skills/codebase-context/SKILL.md +139 -0
  53. package/skills/debug-ui/SKILL.md +220 -0
  54. package/skills/dev-env-scan/SKILL.md +147 -0
  55. package/skills/dev-host-init/SKILL.md +198 -0
  56. package/skills/dev-host-init/scripts/fill-placeholders.py +226 -0
  57. package/skills/dev-host-init/scripts/host-scan.ps1 +159 -0
  58. package/skills/dev-host-init/scripts/host-scan.sh +201 -0
  59. package/skills/dev-host-init/scripts/render-now.py +488 -0
  60. package/skills/dev-host-init/scripts/tools-catalog.py +229 -0
  61. package/skills/dev-host-init/templates/graph-first-gate.ts +291 -0
  62. package/skills/dev-host-init/templates/host-injection.template.md +725 -0
  63. package/skills/discover-skill-opportunities/SKILL.md +145 -0
  64. package/skills/discover-skill-opportunities/references/accounting-finance-ops.md +24 -0
  65. package/skills/discover-skill-opportunities/references/business-consulting.md +24 -0
  66. package/skills/discover-skill-opportunities/references/evidence-and-privacy.md +39 -0
  67. package/skills/discover-skill-opportunities/references/finance-investment.md +24 -0
  68. package/skills/discover-skill-opportunities/references/legal-and-compliance.md +24 -0
  69. package/skills/discover-skill-opportunities/references/output-contract.md +75 -0
  70. package/skills/discover-skill-opportunities/references/product-and-operations.md +24 -0
  71. package/skills/discover-skill-opportunities/references/quant-trading.md +24 -0
  72. package/skills/discover-skill-opportunities/references/scientific-research.md +24 -0
  73. package/skills/discover-skill-opportunities/references/scoring-rubric.md +45 -0
  74. package/skills/discover-skill-opportunities/references/session-skill-review.md +78 -0
  75. package/skills/discover-skill-opportunities/references/software-development.md +24 -0
  76. package/skills/fork-sync/SKILL.md +86 -0
  77. package/skills/gh-actions-architect/SKILL.md +395 -0
  78. package/skills/goal-driven-development/SKILL.md +132 -0
  79. package/skills/intent-grill/SKILL.md +46 -0
  80. package/skills/iteration-manager/SKILL.md +53 -0
  81. package/skills/loop-engineer/SKILL.md +108 -0
  82. package/skills/nodejs-npm-auto-release/SKILL.md +141 -0
  83. package/skills/prd/SKILL.md +63 -0
  84. package/skills/project-health-audit/SKILL.md +64 -0
  85. package/skills/ralph/SKILL.md +329 -0
  86. package/skills/ralph-yolo/SKILL.md +623 -0
  87. package/skills/security-audit/SKILL.md +114 -0
  88. package/skills/security-audit/references/audit-checklist.md +135 -0
  89. package/skills/security-audit/references/evidence-conventions.md +54 -0
  90. package/skills/security-audit/references/findings-schema.md +37 -0
  91. package/skills/security-audit/references/stack-signatures.md +66 -0
  92. package/skills/shipgate/SKILL.md +40 -0
  93. package/skills/shipgate-install/SKILL.md +87 -0
  94. package/skills/shipgate-quality/SKILL.md +80 -0
  95. package/skills/shipgate-security/SKILL.md +97 -0
  96. package/skills/shipgate-spec/SKILL.md +67 -0
  97. package/skills/ux-experience-audit/SKILL.md +202 -0
  98. package/src/cli.mjs +118 -0
  99. package/src/commands/ask.mjs +82 -0
  100. package/src/commands/deploy.mjs +587 -0
  101. package/src/commands/gates.mjs +83 -0
  102. package/src/commands/policy.mjs +116 -0
  103. package/src/gates/quality.mjs +123 -0
  104. package/src/gates/security.mjs +92 -0
  105. package/src/gates/ship.mjs +74 -0
  106. package/src/gates/spec.mjs +88 -0
  107. package/src/harness/index.mjs +203 -0
  108. package/src/inject/render.mjs +75 -0
  109. package/src/lib/cfg.mjs +66 -0
  110. package/src/lib/duration.mjs +41 -0
  111. package/src/lib/engines.mjs +182 -0
  112. package/src/lib/exec.mjs +80 -0
  113. package/src/lib/fsx.mjs +119 -0
  114. package/src/lib/gate.mjs +329 -0
  115. package/src/lib/log.mjs +31 -0
  116. package/src/lib/skills.mjs +347 -0
  117. package/src/lib/state.mjs +50 -0
  118. package/src/lib/update.mjs +67 -0
  119. package/src/version.mjs +14 -0
  120. package/templates/agents-snippet.md +82 -0
  121. package/templates/dev-profile.schema.json +119 -0
  122. package/templates/prd.json.example +64 -0
  123. package/templates/rule.json.example +28 -0
@@ -0,0 +1,587 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { VERSION, packageRoot } from '../version.mjs';
4
+ import { c, log, table } from '../lib/log.mjs';
5
+ import { backupOnce, earliestBackup, exists, latestBackup, readIfExists, writeText } from '../lib/fsx.mjs';
6
+ import { ensureHarnessRecord, harnessRecord, loadManifest, saveManifest } from '../lib/state.mjs';
7
+ import { allHarnesses, capabilities, detected, getHarness, resolveHarness, selectHarnesses } from '../harness/index.mjs';
8
+ import { installAgents, installCommands, installSkills, listSkillNames, pruneSkills, skillsSource, auditSkillRoot, detectFlatSkillDuplicates, skillsBackupDir } from '../lib/skills.mjs';
9
+ import { blockVersion, cursorFrontmatter, renderBlock, upsertBlock } from '../inject/render.mjs';
10
+ import { gateStatus, installGateBundle, loadPolicy, syncPolicyToHarnesses, detectLegacyGates } from '../lib/gate.mjs';
11
+ import { checkEngines, missingEngineHints, reportEngines, resolveAislop } from '../lib/engines.mjs';
12
+ import { runShipGate } from '../gates/ship.mjs';
13
+ import { run } from '../lib/exec.mjs';
14
+ import { checkLatest, checkedToday, markChecked, selfUpdate } from '../lib/update.mjs';
15
+ import { askSelection, printPlan } from './ask.mjs';
16
+
17
+ function targets(ctx, { includeUndetected = false } = {}) {
18
+ return selectHarnesses({ requested: ctx.flags.harness, cfg: ctx.cfg, includeUndetected });
19
+ }
20
+
21
+ function reportMissing(missing) {
22
+ for (const harness of missing) {
23
+ log.warn(`${harness.label}(${harness.id})未检测到:${harness.detectPath ?? '无探测路径'}`);
24
+ log.info(` ${c.dim('已按显式指定预装;不想预装就不要把它写进 --harness')}`);
25
+ }
26
+ }
27
+
28
+ export function injectOne(harness, cfg, { dryRun = false } = {}) {
29
+ if (!harness.injectPath) return { action: 'none' };
30
+ const block = renderBlock({ version: VERSION, min: cfg.quality.min });
31
+ const frontmatter =
32
+ harness.injectPath.endsWith('.mdc') && readIfExists(harness.injectPath) === null ? cursorFrontmatter() : null;
33
+ return upsertBlock(harness.injectPath, block, { dryRun, frontmatter });
34
+ }
35
+
36
+ export function installOne(ctx, harness, manifest) {
37
+ const dryRun = Boolean(ctx.flags['dry-run']);
38
+ const record = ensureHarnessRecord(manifest, harness.id);
39
+ record.version = VERSION;
40
+ record.managed = true;
41
+
42
+ const skills = installSkills(harness, record, { dryRun });
43
+ const commands = installCommands(harness, record, { dryRun });
44
+ const agents = installAgents(harness, record, { dryRun });
45
+ const gate = installGateBundle(harness, { dryRun });
46
+ const inject = injectOne(harness, ctx.cfg, { dryRun });
47
+
48
+ if (!dryRun && inject.action !== 'none') {
49
+ record.inject = {
50
+ file: harness.injectPath,
51
+ version: blockVersion(renderBlock({ version: VERSION, min: ctx.cfg.quality.min })),
52
+ updatedAt: new Date().toISOString(),
53
+ };
54
+ }
55
+
56
+ const pruned = ctx.flags.prune ? pruneSkills(harness, record, { dryRun }) : [];
57
+
58
+ log.step(`${harness.label} (${harness.id})${dryRun ? c.dim(' — dry-run') : ''}`);
59
+ if (skills.installed.length) log.ok(` skills ${skills.installed.length} 个(共 ${listSkillNames().length} 个可分发)`);
60
+ else if (!harness.skillsPath) log.info(` ${c.dim('skills 跳过:harness 无 skills 目录')}`);
61
+ if (skills.skipped.length) log.info(` ${c.dim(`skills 无变化 ${skills.skipped.length} 个(hash 一致)`)}`);
62
+ if (commands.installed.length) log.ok(` commands ${commands.installed.length} 个`);
63
+ if (commands.overwritten?.length) {
64
+ log.warn(` commands 覆盖了你原有的 ${commands.overwritten.length} 个同名文件(已备份 *.shipgate-bak.*):${commands.overwritten.slice(0, 5).join(', ')}${commands.overwritten.length > 5 ? ' …' : ''}`);
65
+ }
66
+ if (commands.skippedReason) log.info(` ${c.dim(`commands 跳过:${commands.skippedReason}`)}`);
67
+ if (agents.installed.length) log.ok(` agents ${agents.installed.length} 个`);
68
+ if (agents.overwritten?.length) {
69
+ log.warn(` agents 覆盖了你原有的 ${agents.overwritten.length} 个同名文件(已备份):${agents.overwritten.join(', ')}`);
70
+ }
71
+ if (agents.skippedReason) log.info(` ${c.dim(`agents 跳过:${agents.skippedReason}`)}`);
72
+ if (harness.gateDest) log.ok(` 硬门控 → ${harness.gateDest}(${gate.kind} 适配,policy 已合并)`);
73
+ if (inject.action !== 'none') log.ok(` 注入 → ${harness.injectPath} [${inject.action}]`);
74
+ for (const name of pruned) log.info(` ${c.dim(`已清理旧 skill ${name}`)}`);
75
+ }
76
+
77
+ const PI_EXTENSIONS = {
78
+ 'goal-mode': 'goal-mode.ts',
79
+ 'auto-continue': 'auto-continue.ts',
80
+ };
81
+
82
+ /**
83
+ * Opt-in continuation extensions for pi. Deliberately outside the default
84
+ * install path: they change how long an agent keeps running, which is a runtime
85
+ * policy the operator must ask for, not something a skill pack turns on.
86
+ */
87
+ function installPiExtension(ctx, name, { dryRun }) {
88
+ const pi = resolveHarness(getHarness('pi', ctx.cfg));
89
+ if (!detected(pi)) {
90
+ log.warn(`--with-${name}:未探测到 pi(${pi.detectPath ?? '无探测路径'}),跳过`);
91
+ return { action: 'skipped' };
92
+ }
93
+ const src = path.join(packageRoot(), 'assets', 'pi-extensions', PI_EXTENSIONS[name]);
94
+ if (!exists(src)) {
95
+ log.err(`续跑扩展源码缺失:${src}`);
96
+ return { action: 'missing-source' };
97
+ }
98
+ const destDir = path.join(pi.detectPath, 'agent', 'extensions');
99
+ const dest = path.join(destDir, PI_EXTENSIONS[name]);
100
+ if (exists(dest)) {
101
+ if (!dryRun) backupOnce(dest);
102
+ log.warn(`${dest} 已存在,已备份为 *.shipgate-bak.* 后覆盖`);
103
+ }
104
+ if (!dryRun) {
105
+ fs.mkdirSync(destDir, { recursive: true });
106
+ fs.copyFileSync(src, dest);
107
+ }
108
+ log.ok(`续跑扩展 → ${dest}${dryRun ? '(dry-run,不写盘)' : ''}`);
109
+ return { action: dryRun ? 'would-install' : 'installed', dest };
110
+ }
111
+
112
+ /**
113
+ * Report-only: gate artefacts left by agent-config-bridge would load alongside
114
+ * ShipGate's bundle. Never deleted automatically — the operator gets the exact
115
+ * command and decides.
116
+ */
117
+ function moveIntoDirCommand(from, dir) {
118
+ return process.platform === 'win32'
119
+ ? `New-Item -ItemType Directory -Force "${dir}" | Out-Null; Move-Item "${from}" "${dir}"`
120
+ : `mkdir -p "${dir}" && mv "${from}" "${dir}"`;
121
+ }
122
+
123
+ /**
124
+ * Report-only: gate artefacts left by agent-config-bridge would load alongside
125
+ * ShipGate's bundle. Never deleted automatically — the operator gets the exact
126
+ * command and decides.
127
+ */
128
+ export function reportLegacyGates(home) {
129
+ const legacy = detectLegacyGates(home ? { home } : {});
130
+ const findings = [];
131
+ if (legacy.bridgePiGate && legacy.shipGatePi) {
132
+ // pi auto-discovers every subdirectory with index.js under extensions/.
133
+ // Renaming to "*.disabled" *inside* that folder still loads it, so the only
134
+ // correct instruction moves it to a sibling directory pi never scans.
135
+ const quarantineDir = path.join(path.dirname(path.dirname(legacy.bridgePiGate)), 'extensions-disabled');
136
+ findings.push({
137
+ code: 'LEGACY_GATE_DUPLICATE',
138
+ level: 'warn',
139
+ message: `pi 同时存在两份门控:${legacy.bridgePiGate}(bridge)与 ${legacy.shipGatePi}(ShipGate)`,
140
+ command: moveIntoDirCommand(legacy.bridgePiGate, quarantineDir),
141
+ });
142
+ }
143
+ if (legacy.legacyOverride) {
144
+ // Not a "second truth": the live gate reads ShipGate's override file and
145
+ // drops `destructive_mode` from ANY override, so the mode written here
146
+ // cannot decide behaviour whichever order things load in. Clutter to
147
+ // delete, therefore info — and the old advice (rename to `.disabled`) was
148
+ // useless precisely because the file kept being read.
149
+ findings.push({
150
+ code: 'LEGACY_OVERRIDE_FILE',
151
+ level: 'info',
152
+ message: `旧 override 文件已停读:${legacy.legacyOverride}(其中的 destructive_mode=${legacy.legacyOverrideMode} 已不生效;grants 与受保护目录由 ~/.config/shipgate/machine-override.json 承接)。可删除。`,
153
+ command:
154
+ process.platform === 'win32'
155
+ ? `Remove-Item "${legacy.legacyOverride}"`
156
+ : `rm -f "${legacy.legacyOverride}"`,
157
+ });
158
+ }
159
+ if (legacy.dshMounted.length > 0 && !legacy.dshMounted.includes('enforce-rules')) {
160
+ findings.push({
161
+ code: 'DSH_GATE_MISMOUNT',
162
+ level: 'warn',
163
+ message: `dsh 挂载的是 ${legacy.dshMounted.join(', ')},不是 ShipGate 的 enforce-rules`,
164
+ command: null,
165
+ });
166
+ }
167
+ return findings;
168
+ }
169
+
170
+ /**
171
+ * Per-edit quality hook is opt-in: it runs aislop on every edit, which is a
172
+ * real cost on a small machine. `--hooks` asks for it explicitly instead of
173
+ * silently wiring a hook into the user's agent.
174
+ */
175
+ function installAislopHooks(ctx, harnesses) {
176
+ const bin = resolveAislop(ctx.cwd);
177
+ if (!bin) {
178
+ log.warn('aislop 未安装,跳过 --hooks(先 npm i -g aislop)');
179
+ return;
180
+ }
181
+ const supported = harnesses.map((h) => h.id).filter((id) => ['claude', 'codex', 'cursor', 'gemini'].includes(id));
182
+ if (supported.length === 0) {
183
+ log.warn('--hooks:所选 harness 不支持 per-edit 钩子');
184
+ return;
185
+ }
186
+ log.title('per-edit quality 钩子');
187
+ for (const id of supported) {
188
+ const result = run(bin, ['hook', 'install', `--${id}`], { timeout: 120_000 });
189
+ if (result.ok) log.ok(`${id} 钩子已安装`);
190
+ else log.warn(`${id} 钩子安装失败:${(result.stderr || result.stdout).split('\n')[0]}`);
191
+ }
192
+ }
193
+
194
+ export async function printUpdateHint() {
195
+ if (checkedToday()) return;
196
+ const result = await checkLatest();
197
+ markChecked();
198
+ if (result.ok && result.outdated) {
199
+ log.warn(`ShipGate 有新版本 ${result.latest}(当前 ${VERSION})→ 运行 \`shipgate update\``);
200
+ }
201
+ }
202
+
203
+ export async function doctor(ctx) {
204
+ const manifest = loadManifest();
205
+ const harnesses = allHarnesses(ctx.cfg).map(resolveHarness);
206
+ const engines = checkEngines(ctx);
207
+ const rows = [];
208
+
209
+ for (const harness of harnesses) {
210
+ const record = harnessRecord(manifest, harness.id) ?? {};
211
+ const caps = capabilities(harness);
212
+ const injectState =
213
+ harness.injectPath && exists(harness.injectPath)
214
+ ? (blockVersion(readIfExists(harness.injectPath) ?? '') ?? 'no-block')
215
+ : 'missing';
216
+ const status = caps.gate ? gateStatus(harness) : null;
217
+ rows.push([
218
+ harness.id,
219
+ detected(harness) ? 'yes' : 'no',
220
+ caps.skills ? `${Object.keys(record.skills ?? {}).length}/${listSkillNames().length}` : '-',
221
+ `${Object.keys(record.commands ?? {}).length}${caps.commands ? '' : '(-)'}`,
222
+ `${Object.keys(record.agents ?? {}).length}${caps.agents ? '' : '(-)'}`,
223
+ injectState,
224
+ status ? (status.installed ? `on(${status.mode})` : 'missing') : '-',
225
+ ]);
226
+ }
227
+
228
+ if (ctx.flags.json) {
229
+ log.plain(JSON.stringify({ version: VERSION, node: process.version, skillCount: listSkillNames().length, harnesses: rows, engines }, null, 2));
230
+ return 0;
231
+ }
232
+
233
+ log.title(`ShipGate ${VERSION} · node ${process.version} · 可分发 skill ${listSkillNames().length} 个`);
234
+ log.plain(table(rows, ['harness', 'found', 'skills', 'cmds', 'agents', 'inject', 'gate']));
235
+
236
+ log.title('引擎');
237
+ reportEngines(engines);
238
+ const py = engines.pythonEngine;
239
+ if (py?.broken) {
240
+ log.warn('AISLOP_PYTHON_ENGINE_UNUSABLE:aislop 自带的 Python 引擎与本机 GLIBC 不兼容');
241
+ log.info(` ${c.dim(`路径 ${py.path}(需要 GLIBC ≥ 2.34,本机 ${py.glibc})`)}`);
242
+ log.info(` ${c.dim('它会让 ruff 输出为空,quality 闸因此报“引擎错误”——那是环境问题,不是代码问题')}`);
243
+ log.info(` chmod a-x "${py.path}" ${c.dim('# 去掉可执行位,aislop 回退到 PATH 上的 ruff')}`);
244
+ }
245
+
246
+ const nodeMajor = Number.parseInt(process.version.slice(1), 10);
247
+ if (nodeMajor < 20) log.err(`node ${process.version} 低于最低要求 20`);
248
+
249
+ const policy = loadPolicy();
250
+ log.title('硬门控策略');
251
+ log.plain(`${policy.config.destructive_mode} · 受保护工作区 ${policy.config.protected_worktrees.length} 条`);
252
+ // 只把真正装了的算“硬拦截”;声明了 gate 但本机未装的 harness 单独列出,
253
+ // 否则未安装的 dsh 也会被误报成受硬门控保护。
254
+ const gated = harnesses.filter((h) => h.gateDest && detected(h) && gateStatus(h).installed).map((h) => h.id);
255
+ const gatedNotInstalled = harnesses.filter((h) => h.gateDest && (!detected(h) || !gateStatus(h).installed)).map((h) => h.id);
256
+ const soft = harnesses.filter((h) => !h.gateDest && detected(h)).map((h) => h.id);
257
+ if (gated.length) log.info(` ${c.yellow('硬拦截')}:${gated.join(', ')}`);
258
+ if (gatedNotInstalled.length) log.info(` ${c.dim(`支持硬门控但未安装:${gatedNotInstalled.join(', ')}`)}`);
259
+ if (soft.length) log.info(` ${c.dim(`软约束:${soft.join(', ')}(skills + 注入,无进程级拦截)`)}`);
260
+ // zcode is deliberately not built in: a GUI IDE with its own agent kernel, and
261
+ // no ~/.zcode on this machine. Say so rather than silently omitting it.
262
+ log.info(
263
+ ` ${c.dim('未纳入:zcode(智谱 GUI IDE,自有内核;未探测到 ~/.zcode;出现 ~/.zcode/skills 时用 custom 接入)')}`,
264
+ );
265
+
266
+ // Skill roots are shared, not per-harness: pi and dsh both read
267
+ // ~/.agents/skills, which is a link to ~/.claude/skills. Dedupe by real path
268
+ // so the same defect is reported once, with every sharer named.
269
+ const roots = new Map();
270
+ for (const harness of harnesses) {
271
+ if (!harness.skillsPath || !fs.existsSync(harness.skillsPath)) continue;
272
+ const real = fs.realpathSync(harness.skillsPath);
273
+ const entry = roots.get(real) ?? { dir: real, shared: [] };
274
+ entry.shared.push(harness.id);
275
+ roots.set(real, entry);
276
+ }
277
+ const hygiene = [];
278
+ for (const { dir, shared } of roots.values()) {
279
+ const audit = auditSkillRoot(dir);
280
+ const flat = detectFlatSkillDuplicates(dir);
281
+ if (!flat.length && !audit.strayDirs.length && !audit.collisions.length && !audit.invalidNames.length && !audit.longDescriptions.length) {
282
+ continue;
283
+ }
284
+ hygiene.push({ dir, shared, audit, flat });
285
+ }
286
+ if (hygiene.length) {
287
+ log.title('skill 根卫生(只报告,不自动移)');
288
+ for (const { dir, shared, audit, flat } of hygiene) {
289
+ log.info(` ${dir}${shared.length > 1 ? `(被 ${shared.join(', ')} 共用,同一份)` : ''}`);
290
+ // Flat `<name>.md` next to `<name>/SKILL.md` declares the same skill twice.
291
+ if (flat.length) {
292
+ log.warn(` FLAT_SKILL_DUPLICATE:${flat.length} 个扁平 .md 与同名目录并存`);
293
+ log.info(` 同名:${flat.slice(0, 8).join(', ')}${flat.length > 8 ? ' …' : ''}`);
294
+ const backup = skillsBackupDir('skills-flat');
295
+ const names = flat.map((n) => (process.platform === 'win32' ? `'${n}'` : n)).join(', ');
296
+ if (process.platform === 'win32') {
297
+ log.info(` ${c.dim(`New-Item -ItemType Directory -Force "${backup}" | Out-Null`)}`);
298
+ log.info(
299
+ ` ${c.dim(`Get-ChildItem "${dir}" -Filter *.md | Where-Object { $_.BaseName -in @(${names}) } | Move-Item -Destination "${backup}"`)}`,
300
+ );
301
+ } else {
302
+ log.info(` ${c.dim(`mkdir -p "${backup}" && mv "${dir}"/{${names}}.md "${backup}"/`)}`);
303
+ }
304
+ }
305
+ for (const stray of audit.strayDirs) {
306
+ log.warn(` SKILL_STRAY_DIR:${stray.dir} 有 ${stray.mdCount} 个 .md 但没有 SKILL.md`);
307
+ log.info(` ${c.dim('一旦这个目录被当成 skill path 传入,其中的 .md 就会变成以目录名命名的 skill')}`);
308
+ log.info(` ${c.dim(moveIntoDirCommand(stray.dir, skillsBackupDir('skills-stray')))}`);
309
+ }
310
+ for (const item of audit.collisions) {
311
+ log.warn(` SKILL_NAME_COLLISION:"${item.name}" 被 ${item.losers.length + 1} 个文件声明`);
312
+ log.info(` 生效:${item.winner}`);
313
+ for (const loser of item.losers) log.info(` ${c.dim(`被跳过:${loser}`)}`);
314
+ }
315
+ for (const item of audit.invalidNames) {
316
+ log.warn(` SKILL_INVALID_NAME:${item.name}(${item.file})`);
317
+ log.info(` ${c.dim(item.messages.join(';'))}`);
318
+ }
319
+ for (const item of audit.longDescriptions) {
320
+ log.warn(` SKILL_DESCRIPTION_TOO_LONG:${item.file} 的 description 有 ${item.length} 字符`);
321
+ log.info(` ${c.dim(`上限 ${1024};在源 skill 里压短,不要改已分发副本`)}`);
322
+ }
323
+ }
324
+ }
325
+
326
+ const legacy = reportLegacyGates();
327
+ if (legacy.length > 0) {
328
+ log.title('遗留门控(只报告,不自动删)');
329
+ for (const item of legacy) {
330
+ const line = ` ${item.code}:${item.message}`;
331
+ if (item.level === 'info') log.info(line);
332
+ else log.warn(line);
333
+ if (item.command) log.info(` ${c.dim(`停用命令:${item.command}`)}`);
334
+ }
335
+ }
336
+
337
+ const managed = harnesses.filter((h) => Object.keys(harnessRecord(manifest, h.id)?.skills ?? {}).length);
338
+ const ship = runShipGate({ harnesses: managed, manifest, skillsSource: skillsSource() });
339
+ log.title('产物一致性');
340
+ log.plain(`${ship.ok ? c.green('✔') : c.red('✖')} ${ship.summary}`);
341
+ for (const finding of ship.findings.slice(0, 10)) log.info(` ${c.dim(`${finding.harness ?? ''} ${finding.message}`)}`);
342
+
343
+ // A health check that prints ✖ and exits 0 is a decoration, not a gate.
344
+ return ship.ok ? 0 : 1;
345
+ }
346
+
347
+ export async function install(ctx) {
348
+ const dryRun = Boolean(ctx.flags['dry-run']);
349
+ // goal-mode and auto-continue both drive the turn boundary; enabling both
350
+ // would make the agent fight itself over when to continue.
351
+ if (ctx.flags['with-goal-mode'] && ctx.flags['with-auto-continue']) {
352
+ log.err('--with-goal-mode 与 --with-auto-continue 互斥:二选一');
353
+ return 2;
354
+ }
355
+ const allDetected = allHarnesses(ctx.cfg).map(resolveHarness).filter(detected);
356
+ let selected = [];
357
+ let missing = [];
358
+
359
+ if (ctx.flags.ask && !ctx.flags.harness && !ctx.flags.yes) {
360
+ if (allDetected.length === 0) {
361
+ log.err('没有探测到任何 harness(检查 ~/.claude / ~/.pi / ~/.codex 等目录)');
362
+ return 3;
363
+ }
364
+ printPlan(allDetected, ctx.cfg);
365
+ const answer = await askSelection(allDetected);
366
+ if (answer.note) log.info(c.dim(answer.note));
367
+ if (answer.selected.length === 0) {
368
+ log.warn('未选择任何 harness,已取消');
369
+ return 0;
370
+ }
371
+ selected = answer.selected;
372
+ } else {
373
+ const picked = targets(ctx, { includeUndetected: true });
374
+ selected = picked.selected;
375
+ missing = picked.missing;
376
+ reportMissing(missing);
377
+ if (ctx.flags.yes) log.info(c.dim(`--yes:不需要交互,按选定的 harness 执行(${selected.map((h) => h.id).join(', ')})`));
378
+ if (selected.length > 0) printPlan(selected, ctx.cfg);
379
+ }
380
+
381
+ if (selected.length === 0) {
382
+ log.err('没有可安装的 harness(用 --harness 指定,或检查 ~/.claude ~/.pi 等目录)');
383
+ return 3;
384
+ }
385
+
386
+ const manifest = loadManifest();
387
+ log.title(`安装到 ${selected.length} 个 harness${dryRun ? '(dry-run,不写盘)' : ''}`);
388
+ for (const harness of selected) installOne(ctx, harness, manifest);
389
+
390
+ if (!dryRun) {
391
+ saveManifest(manifest);
392
+ const gated = selected.filter((h) => h.gateDest).map(resolveHarness);
393
+ if (gated.length > 0) {
394
+ const touched = syncPolicyToHarnesses(gated, { dryRun: false });
395
+ for (const item of touched) log.ok(`policy 同步 → ${item.harness}(${item.mode} / ${item.protected} 条受保护)`);
396
+ }
397
+ }
398
+
399
+ const engines = checkEngines(ctx);
400
+ log.title('引擎');
401
+ const missingEngines = missingEngineHints(engines);
402
+ reportEngines(engines, { withPath: false });
403
+ if (missingEngines.length === 0 && !dryRun) {
404
+ log.info(c.dim('提示:quality 的 per-edit 钩子需显式启用 → shipgate install --hooks 或 aislop hook install --claude'));
405
+ }
406
+
407
+ if (ctx.flags.hooks && !dryRun) installAislopHooks(ctx, selected);
408
+
409
+ if (ctx.flags['with-goal-mode']) installPiExtension(ctx, 'goal-mode', { dryRun });
410
+ if (ctx.flags['with-auto-continue']) installPiExtension(ctx, 'auto-continue', { dryRun });
411
+
412
+ const legacyFindings = reportLegacyGates();
413
+ if (legacyFindings.length > 0) {
414
+ log.title('遗留门控提醒(不自动删)');
415
+ for (const item of legacyFindings) {
416
+ log.warn(` ${item.code}:${item.message}`);
417
+ if (item.command) log.info(` ${c.dim(`停用命令:${item.command}`)}`);
418
+ }
419
+ }
420
+
421
+ if (!dryRun) await maybeAutoUpdate(ctx);
422
+ else log.info(c.dim('dry-run 结束;去掉 --dry-run 才会写盘'));
423
+ return 0;
424
+ }
425
+
426
+ export async function maybeAutoUpdate(ctx) {
427
+ if (!ctx.cfg.update?.autoUpdate) return;
428
+ const result = await checkLatest();
429
+ markChecked();
430
+ if (!result.ok || !result.outdated) return;
431
+ log.step(`检测到新版本 ${result.latest},自动更新中`);
432
+ const updated = selfUpdate();
433
+ if (!updated.ok) {
434
+ log.warn(`自动更新失败(不影响当前部署):${updated.stderr.split('\n')[0]}`);
435
+ return;
436
+ }
437
+ log.ok('已更新;重装 skills / commands / agents 与注入区块');
438
+ const manifest = loadManifest();
439
+ for (const harness of allHarnesses(ctx.cfg).map(resolveHarness).filter(detected)) installOne(ctx, harness, manifest);
440
+ saveManifest(manifest);
441
+ }
442
+
443
+ export async function inject(ctx) {
444
+ const { selected, missing } = targets(ctx, { includeUndetected: true });
445
+ reportMissing(missing);
446
+ log.title('重渲染注入区块');
447
+ for (const harness of selected) {
448
+ const result = injectOne(harness, ctx.cfg, { dryRun: Boolean(ctx.flags['dry-run']) });
449
+ if (result.action === 'none') log.info(c.dim(`${harness.id}: 无注入文件,跳过`));
450
+ else log.ok(`${harness.id} → ${harness.injectPath} [${result.action}]`);
451
+ }
452
+ return 0;
453
+ }
454
+
455
+ export function status(ctx) {
456
+ const manifest = loadManifest();
457
+ const harnesses = allHarnesses(ctx.cfg).map(resolveHarness);
458
+ const managed = harnesses.filter((h) => Object.keys(harnessRecord(manifest, h.id)?.skills ?? {}).length);
459
+ // --strict turns the read-only view into the ship gate's verdict, so CI can
460
+ // fail on drift. Without it the command stays a plain status table.
461
+ const ship = ctx.flags.strict ? runShipGate({ harnesses: managed, manifest, skillsSource: skillsSource() }) : null;
462
+ const rows = harnesses.map((harness) => {
463
+ const record = harnessRecord(manifest, harness.id);
464
+ const gate = harness.gateDest ? gateStatus(harness) : null;
465
+ return [
466
+ harness.id,
467
+ record?.managed ? 'managed' : record ? 'installed' : '-',
468
+ String(Object.keys(record?.skills ?? {}).length),
469
+ String(Object.keys(record?.commands ?? {}).length),
470
+ String(Object.keys(record?.agents ?? {}).length),
471
+ record?.inject?.version ?? '-',
472
+ record?.version ?? '-',
473
+ gate ? (gate.installed ? gate.mode : 'missing') : '-',
474
+ ];
475
+ });
476
+
477
+ if (ctx.flags.json) {
478
+ const payload = ship ? { version: VERSION, manifest, rows, ship: { ok: ship.ok, findings: ship.findings } } : { version: VERSION, manifest, rows };
479
+ log.plain(JSON.stringify(payload, null, 2));
480
+ return ship && !ship.ok ? 1 : 0;
481
+ }
482
+ log.title('ShipGate 受管状态');
483
+ log.plain(table(rows, ['harness', 'state', 'skills', 'cmds', 'agents', 'inject', 'version', 'gate']));
484
+ if (ship && !ship.ok) {
485
+ log.title('产物一致性');
486
+ log.plain(`${c.red('✖')} ${ship.summary}`);
487
+ for (const finding of ship.findings.slice(0, 10)) log.info(` ${c.dim(`${finding.harness ?? ''} ${finding.message}`)}`);
488
+ }
489
+ return ship && !ship.ok ? 1 : 0;
490
+ }
491
+
492
+ function pickIds(ctx) {
493
+ const raw = ctx.flags.harness ?? ctx.args[0] ?? '';
494
+ return String(raw)
495
+ .split(',')
496
+ .map((s) => s.trim())
497
+ .filter(Boolean);
498
+ }
499
+
500
+ export function adopt(ctx) {
501
+ const ids = pickIds(ctx);
502
+ if (ids.length === 0) {
503
+ log.err('用法:shipgate adopt <harness>');
504
+ return 2;
505
+ }
506
+ const manifest = loadManifest();
507
+ for (const id of ids) {
508
+ const harness = resolveHarness(getHarness(id, ctx.cfg));
509
+ if (harness.injectPath) backupOnce(harness.injectPath);
510
+ ensureHarnessRecord(manifest, id).managed = true;
511
+ log.ok(`${id} 已纳入 ShipGate 受管`);
512
+ }
513
+ saveManifest(manifest);
514
+ return 0;
515
+ }
516
+
517
+ export function revoke(ctx) {
518
+ const ids = pickIds(ctx);
519
+ if (ids.length === 0) {
520
+ log.err('用法:shipgate revoke <harness>');
521
+ return 2;
522
+ }
523
+ const manifest = loadManifest();
524
+ for (const id of ids) {
525
+ const harness = resolveHarness(getHarness(id, ctx.cfg));
526
+ // revoke 要回到 ShipGate 动手之前那个版本:只有最早的备份是干净的,
527
+ // 用最新备份会把上一版注入区块装回去,等于没撤。
528
+ const backup = harness.injectPath ? earliestBackup(harness.injectPath) : null;
529
+ if (backup) {
530
+ writeText(harness.injectPath, readIfExists(backup) ?? '');
531
+ log.ok(`${id} 注入文件已恢复为最初版本:${path.basename(backup)}`);
532
+ } else {
533
+ log.warn(`${id} 没有可用备份,未改动注入文件`);
534
+ }
535
+ delete manifest.harnesses[id];
536
+ }
537
+ saveManifest(manifest);
538
+ return 0;
539
+ }
540
+
541
+ export function rollback(ctx) {
542
+ const ids = pickIds(ctx);
543
+ if (ids.length === 0) {
544
+ log.err('用法:shipgate rollback <harness>');
545
+ return 2;
546
+ }
547
+ for (const id of ids) {
548
+ const harness = resolveHarness(getHarness(id, ctx.cfg));
549
+ const backup = harness.injectPath ? latestBackup(harness.injectPath) : null;
550
+ if (!backup) {
551
+ log.warn(`${id} 没有可用备份`);
552
+ continue;
553
+ }
554
+ writeText(harness.injectPath, readIfExists(backup) ?? '');
555
+ log.ok(`${id} 已回滚到 ${path.basename(backup)}`);
556
+ }
557
+ return 0;
558
+ }
559
+
560
+ export async function update(ctx) {
561
+ const result = await checkLatest();
562
+ if (ctx.flags.check) {
563
+ if (ctx.flags.json) {
564
+ log.plain(JSON.stringify(result, null, 2));
565
+ } else if (!result.ok) {
566
+ log.warn(`无法检查更新(${result.error});当前 ${VERSION}`);
567
+ } else if (result.outdated) {
568
+ log.info(`有新版本 ${result.latest}(当前 ${VERSION})→ shipgate update`);
569
+ } else {
570
+ log.ok(`已是最新 ${VERSION}`);
571
+ }
572
+ return 0;
573
+ }
574
+
575
+ if (!result.ok) log.warn(`无法检查更新(${result.error}),仍继续执行全局重装`);
576
+ log.step('npm i -g shipgate-cli@latest');
577
+ const applied = selfUpdate();
578
+ if (!applied.ok) {
579
+ log.err(`自更新失败:${applied.stderr.split('\n')[0] || applied.code}`);
580
+ return 3;
581
+ }
582
+ log.ok('已更新;重装 skills / commands / agents 与注入区块');
583
+ const manifest = loadManifest();
584
+ for (const harness of allHarnesses(ctx.cfg).map(resolveHarness).filter(detected)) installOne(ctx, harness, manifest);
585
+ saveManifest(manifest);
586
+ return 0;
587
+ }
@@ -0,0 +1,83 @@
1
+ import { c, log, table } from '../lib/log.mjs';
2
+ import { runSpecGate } from '../gates/spec.mjs';
3
+ import { runQualityGate } from '../gates/quality.mjs';
4
+ import { runSecurityGate } from '../gates/security.mjs';
5
+ import { checkEngines, missingEngineHints } from '../lib/engines.mjs';
6
+
7
+ const GATE_ROWS = [
8
+ ['spec', '任何代码改动之前', 'shipgate spec check', '内置(CHG 三件套)'],
9
+ ['quality', '每次编辑后 / 提交前', 'shipgate quality', 'aislop(外部依赖)'],
10
+ ['security', '提交前 / 发布前(显式)', 'shipgate security --scope <file>', 'cbh(外部依赖)'],
11
+ ['ship', '装 / 升级 / 换 harness 后', 'shipgate status', '内置(manifest 校验)'],
12
+ ];
13
+
14
+ export function listGates(ctx) {
15
+ const engines = checkEngines(ctx);
16
+ // Only the engines that are really absent get a hint. The old code printed
17
+ // "缺失引擎:…" unconditionally, so `shipgate gates` said `ok ok` and then
18
+ // told the operator to install both.
19
+ const missing = missingEngineHints(engines);
20
+ const withOk = Object.fromEntries(
21
+ Object.entries(engines)
22
+ // pythonEngine is a sub-probe of aislop, not an engine; doctor reports it separately.
23
+ .filter(([name]) => name !== 'pythonEngine')
24
+ .map(([name, info]) => [name, { ...info, ok: Boolean(info?.bin) }]),
25
+ );
26
+
27
+ if (ctx.flags.json) {
28
+ log.plain(
29
+ JSON.stringify(
30
+ { gates: GATE_ROWS.map(([gate, when, command, engine]) => ({ gate, when, command, engine })), engines: withOk },
31
+ null,
32
+ 2,
33
+ ),
34
+ );
35
+ return 0;
36
+ }
37
+
38
+ log.title('ShipGate 四道闸');
39
+ log.plain(table(GATE_ROWS, ['gate', '什么时候过', '命令', '引擎']));
40
+ log.title('引擎');
41
+ log.plain(
42
+ Object.entries(withOk)
43
+ .map(([name, info]) => `${name} ${info.ok ? c.green('ok') : c.red('missing')}`)
44
+ .join(' '),
45
+ );
46
+ if (missing.length > 0) {
47
+ log.info('缺失引擎:');
48
+ for (const item of missing) log.info(` ${item.name} → ${item.install}`);
49
+ }
50
+ return 0;
51
+ }
52
+
53
+ function emitVerdict(ctx, verdict) {
54
+ if (ctx.flags.json) {
55
+ log.plain(JSON.stringify(verdict, null, 2));
56
+ } else {
57
+ const mark = verdict.ok ? c.green('✔') : c.red('✖');
58
+ log.plain(`${mark} [${verdict.gate}] ${verdict.summary}`);
59
+ for (const finding of verdict.findings?.slice(0, 20) ?? []) {
60
+ const where = finding.file ?? finding.harness ?? '';
61
+ log.info(` ${c.dim(where)} ${finding.message}`);
62
+ }
63
+ if (!verdict.ok && verdict.evidence?.install) log.info(` → ${verdict.evidence.install}`);
64
+ if (!verdict.ok && verdict.evidence?.example) log.info(` → 例:${verdict.evidence.example}`);
65
+ }
66
+ return verdict.code;
67
+ }
68
+
69
+ export function specGate(ctx) {
70
+ const dir = ctx.args[0] ?? ctx.cfg.spec.dir;
71
+ return emitVerdict(ctx, runSpecGate({ cwd: ctx.cwd, dir }));
72
+ }
73
+
74
+ export function qualityGate(ctx) {
75
+ const target = ctx.args[0] ?? '.';
76
+ const min = Number.parseInt(ctx.flags.min ?? ctx.cfg.quality.min, 10);
77
+ return emitVerdict(ctx, runQualityGate({ cwd: ctx.cwd, target, min }));
78
+ }
79
+
80
+ export function securityGate(ctx) {
81
+ const scope = ctx.flags.scope ?? ctx.cfg.security?.scope ?? null;
82
+ return emitVerdict(ctx, runSecurityGate({ cwd: ctx.cwd, scope, dryRun: Boolean(ctx.flags['dry-run']) }));
83
+ }