shipgate-cli 0.0.0-stage → 0.2.1

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 (122) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +258 -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 +1121 -0
  10. package/assets/gates/pi/policy.json +93 -0
  11. package/assets/gates/policy.js +4199 -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 +215 -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 +117 -0
  99. package/src/commands/ask.mjs +82 -0
  100. package/src/commands/deploy.mjs +589 -0
  101. package/src/commands/gates.mjs +83 -0
  102. package/src/commands/policy.mjs +67 -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/engines.mjs +182 -0
  111. package/src/lib/exec.mjs +80 -0
  112. package/src/lib/fsx.mjs +119 -0
  113. package/src/lib/gate.mjs +288 -0
  114. package/src/lib/log.mjs +31 -0
  115. package/src/lib/skills.mjs +347 -0
  116. package/src/lib/state.mjs +41 -0
  117. package/src/lib/update.mjs +67 -0
  118. package/src/version.mjs +14 -0
  119. package/templates/agents-snippet.md +82 -0
  120. package/templates/dev-profile.schema.json +119 -0
  121. package/templates/prd.json.example +64 -0
  122. package/templates/rule.json.example +28 -0
@@ -0,0 +1,288 @@
1
+ import path from 'node:path';
2
+ import { HOME } from './cfg.mjs';
3
+ import { stateDir } from './state.mjs';
4
+ import { packageRoot } from '../version.mjs';
5
+ import { backupOnce, copyTree, exists, listDir, readIfExists, writeText } from './fsx.mjs';
6
+
7
+ const DEFAULT_POLICY = {
8
+ config: {
9
+ destructive_mode: 'enforce',
10
+ destructive_mode_until: 0,
11
+ protected_worktrees: [],
12
+ },
13
+ };
14
+
15
+ export function globalPolicyPath() {
16
+ return path.join(stateDir(), 'gate-policy.json');
17
+ }
18
+
19
+ export function gatesSource() {
20
+ return path.join(packageRoot(), 'assets', 'gates');
21
+ }
22
+
23
+ /**
24
+ * Single source of truth for gate policy. Harness policy.json files are
25
+ * projections of this file, so `policy --sync` can always rebuild them.
26
+ */
27
+ export function loadPolicy() {
28
+ const text = readIfExists(globalPolicyPath());
29
+ if (text === null) return structuredClone(DEFAULT_POLICY);
30
+ try {
31
+ const parsed = JSON.parse(text);
32
+ return { ...structuredClone(DEFAULT_POLICY), ...parsed, config: { ...DEFAULT_POLICY.config, ...(parsed.config ?? {}) } };
33
+ } catch (error) {
34
+ throw new Error(`gate-policy.json 损坏,请检查 ${globalPolicyPath()}:${error.message}`);
35
+ }
36
+ }
37
+
38
+ export function savePolicy(policy) {
39
+ writeText(globalPolicyPath(), JSON.stringify(policy, null, 2) + '\n');
40
+ return policy;
41
+ }
42
+
43
+ function normalizeDir(dir) {
44
+ return path.resolve(dir.startsWith('~') ? path.join(HOME, dir.slice(1)) : dir);
45
+ }
46
+
47
+ export function addProtected(dir) {
48
+ const policy = loadPolicy();
49
+ const target = normalizeDir(dir);
50
+ const list = policy.config.protected_worktrees ?? [];
51
+ if (!list.includes(target)) list.push(target);
52
+ policy.config.protected_worktrees = list;
53
+ return savePolicy(policy);
54
+ }
55
+
56
+ export function removeProtected(dir) {
57
+ const policy = loadPolicy();
58
+ const target = normalizeDir(dir);
59
+ policy.config.protected_worktrees = (policy.config.protected_worktrees ?? []).filter((p) => p !== target);
60
+ return savePolicy(policy);
61
+ }
62
+
63
+ export function setMode(mode) {
64
+ if (!['enforce', 'bypass'].includes(mode)) {
65
+ throw new Error(`destructive_mode 只能是 enforce 或 bypass,收到:${mode}`);
66
+ }
67
+ const policy = loadPolicy();
68
+ policy.config.destructive_mode = mode;
69
+ policy.config.destructive_mode_until = 0;
70
+ return savePolicy(policy);
71
+ }
72
+
73
+ /**
74
+ * Merge rule: the base document supplies the rules (checks / reminder /
75
+ * description / version), `config` is layered as base defaults ← harness-local
76
+ * ← global truth, and protected worktrees are unioned so a harness never
77
+ * silently loses a protection the operator just added.
78
+ *
79
+ * The global policy deliberately contributes **only** `config`: it used to be
80
+ * spread whole, which let one harness's stale copy become the next harness's
81
+ * shipped rules.
82
+ */
83
+ export function mergePolicy(globalPolicy, base, harnessConfig = {}) {
84
+ const document = base && typeof base === 'object' ? base : {};
85
+ const baseConfig = document.config && typeof document.config === 'object' ? document.config : {};
86
+ const localConfig = harnessConfig && typeof harnessConfig === 'object' ? harnessConfig : {};
87
+ const union = [
88
+ ...new Set([
89
+ ...(globalPolicy.config.protected_worktrees ?? []),
90
+ ...(localConfig.protected_worktrees ?? []),
91
+ ...(baseConfig.protected_worktrees ?? []),
92
+ ]),
93
+ ];
94
+ return {
95
+ ...document,
96
+ config: { ...baseConfig, ...localConfig, ...globalPolicy.config, protected_worktrees: union },
97
+ };
98
+ }
99
+
100
+ function readJson(file) {
101
+ const text = readIfExists(file);
102
+ if (text === null) return null;
103
+ try {
104
+ return JSON.parse(text);
105
+ } catch {
106
+ // A malformed harness policy is not silently discarded: we keep the raw
107
+ // file under a backup name and let the caller re-seed from global policy.
108
+ return { __malformed: true };
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Sync projection: the global policy is authoritative, so protected worktrees
114
+ * are replaced rather than unioned. Unioning here would make --rm-protected
115
+ * impossible to apply (the removed entry keeps coming back from the harness
116
+ * copy). Union happens exactly once, at install time, and is then promoted
117
+ * back to the global file.
118
+ */
119
+ export function projectPolicy(globalPolicy, existing) {
120
+ const base = existing && typeof existing === 'object' ? existing : {};
121
+ const existingConfig = base.config && typeof base.config === 'object' ? base.config : {};
122
+ return {
123
+ ...base,
124
+ config: {
125
+ ...existingConfig,
126
+ ...globalPolicy.config,
127
+ protected_worktrees: [...(globalPolicy.config.protected_worktrees ?? [])],
128
+ },
129
+ };
130
+ }
131
+
132
+ /**
133
+ * Entry point each harness loads. The vendored `assets/gates/index.js` is the pi
134
+ * entry; copying it verbatim hands dsh a pi plugin, so the matching entry is
135
+ * written at install time.
136
+ */
137
+ const GATE_ENTRY = {
138
+ pi: "// pi loads a directory's index.js as the extension entry.\nexport { default } from './pi/index.js';\n",
139
+ dsh: "// dsh mounts a module specifier; index.js stays a valid entry too.\nexport { apply, inject } from './dsh/index.js';\n",
140
+ };
141
+
142
+ /** The shipped policy document for one harness kind (pi v6 / dsh v7), or null. */
143
+ export function shippedPolicy(kind) {
144
+ const parsed = readJson(path.join(gatesSource(), kind, 'policy.json'));
145
+ return parsed && !parsed.__malformed ? parsed : null;
146
+ }
147
+
148
+ export function installGateBundle(harness, { dryRun = false } = {}) {
149
+ if (!harness.gateDest) return { action: 'none' };
150
+ const source = gatesSource();
151
+ if (!exists(source)) return { action: 'missing-source', source };
152
+
153
+ const kind = harness.gate?.kind ?? 'pi';
154
+ const target = path.join(harness.gateDest, 'policy.json');
155
+ const existing = readJson(target);
156
+ const globalPolicy = loadPolicy();
157
+
158
+ // The document must come from the shipped per-kind file. Promoting whatever
159
+ // the harness already had is exactly how a stale v5 copy overwrote the v6/v7
160
+ // rules on the next install.
161
+ const shipped = shippedPolicy(kind);
162
+ const current = existing && !existing.__malformed ? existing : null;
163
+ const base = shipped ?? current ?? globalPolicy;
164
+ const localConfig = current?.config ?? {};
165
+ const merged = mergePolicy(globalPolicy, base, localConfig);
166
+
167
+ if (!dryRun) {
168
+ copyTree(source, harness.gateDest, { skip: ['policy.json'] });
169
+ if (exists(target)) backupOnce(target);
170
+ writeText(target, JSON.stringify(merged, null, 2) + '\n');
171
+ writeText(path.join(harness.gateDest, 'index.js'), GATE_ENTRY[kind] ?? GATE_ENTRY.pi);
172
+ if (kind === 'dsh') {
173
+ // dsh loads the bundle as ESM. Without this, Node resolves `.js` as
174
+ // CommonJS and the plugin dies on `export` before any rule can run.
175
+ writeText(path.join(harness.gateDest, 'package.json'), JSON.stringify({ type: 'module' }, null, 2) + '\n');
176
+ }
177
+ // The truth source keeps CONFIG only: promoting the document is what made
178
+ // one harness's copy become the other harness's rules.
179
+ savePolicy({ config: merged.config });
180
+ }
181
+
182
+ return { action: dryRun ? 'would-install' : 'installed', kind, target, version: merged.version ?? null };
183
+ }
184
+
185
+ export function syncPolicyToHarnesses(harnesses, { dryRun = false } = {}) {
186
+ const globalPolicy = loadPolicy();
187
+ const touched = [];
188
+
189
+ for (const harness of harnesses) {
190
+ if (!harness.gateDest) continue;
191
+ const target = path.join(harness.gateDest, 'policy.json');
192
+ if (!exists(harness.gateDest)) continue;
193
+ const existing = readJson(target);
194
+ // A harness whose policy file went missing is re-seeded from its own
195
+ // shipped document, not from whichever document happens to be in truth.
196
+ const base = existing && !existing.__malformed ? existing : shippedPolicy(harness.gate?.kind ?? 'pi');
197
+ const merged = projectPolicy(globalPolicy, base);
198
+ if (!dryRun) {
199
+ if (exists(target)) backupOnce(target);
200
+ writeText(target, JSON.stringify(merged, null, 2) + '\n');
201
+ }
202
+ touched.push({ harness: harness.id, target, mode: merged.config.destructive_mode, protected: merged.config.protected_worktrees.length });
203
+ }
204
+ return touched;
205
+ }
206
+
207
+ export function gateStatus(harness) {
208
+ if (!harness.gateDest) return { installed: false, reason: 'harness 无 gate 配置' };
209
+ if (!exists(harness.gateDest)) return { installed: false, reason: '目录不存在' };
210
+ const policy = readJson(path.join(harness.gateDest, 'policy.json'));
211
+ return {
212
+ installed: exists(path.join(harness.gateDest, 'policy.js')) && exists(path.join(harness.gateDest, 'classifier.js')),
213
+ dir: harness.gateDest,
214
+ mode: policy?.config?.destructive_mode ?? 'unknown',
215
+ protected: policy?.config?.protected_worktrees?.length ?? 0,
216
+ };
217
+ }
218
+
219
+ /**
220
+ * Scan dsh Cordis patch files for the gate row actually composed into the
221
+ * runtime. dsh does not auto-load an extensions directory: whatever the patch
222
+ * points at is what runs, so "installed" alone does not mean "in effect".
223
+ */
224
+ function scanDshMounts(profilesDir) {
225
+ const mounted = [];
226
+ for (const entry of listDir(profilesDir)) {
227
+ if (!entry.isDirectory()) continue;
228
+ const patch = path.join(profilesDir, entry.name, 'cordis.patch.yml');
229
+ const text = readIfExists(patch);
230
+ if (!text) continue;
231
+ for (const line of text.split(/\r?\n/)) {
232
+ if (!/^\s*name\s*:/.test(line)) continue;
233
+ if (/enforce-rules/.test(line)) mounted.push('enforce-rules');
234
+ else if (/agent-config-gates/.test(line)) mounted.push('agent-config-gates');
235
+ else if (/coding-gateways/.test(line)) mounted.push('coding-gateways');
236
+ }
237
+ }
238
+ return [...new Set(mounted)];
239
+ }
240
+
241
+ /**
242
+ * A directory only counts as a gate if it carries the engine. Without this
243
+ * check, any unrelated extension (e.g. a provider gateway that happens to live
244
+ * in the same folder) is mistaken for a second gate — and the operator is told
245
+ * to move an extension whose removal would break their model access.
246
+ */
247
+ function isGateBundle(dir) {
248
+ return exists(path.join(dir, 'policy.js')) || exists(path.join(dir, 'classifier.js'));
249
+ }
250
+
251
+ function otherGateBundles(extensionsDir, ownName) {
252
+ return listDir(extensionsDir)
253
+ .filter((entry) => entry.isDirectory() && entry.name !== ownName)
254
+ .map((entry) => path.join(extensionsDir, entry.name))
255
+ .filter(isGateBundle);
256
+ }
257
+
258
+ /**
259
+ * Detect gate artefacts from agent-config-bridge that would run alongside
260
+ * ShipGate's own bundle. This is a report-only probe: deleting another
261
+ * project's files is never automatic. The caller prints the findings and hands
262
+ * over an explicit command.
263
+ */
264
+ export function detectLegacyGates({ home = HOME } = {}) {
265
+ const piExtDir = path.join(home, '.pi', 'agent', 'extensions');
266
+ const shipGatePi = path.join(piExtDir, 'enforce-rules');
267
+ // bridge's pi gate used install_as "enforce-rules" — the SAME directory
268
+ // ShipGate uses. A second pi gate therefore only exists if some OTHER folder
269
+ // holds a real gate bundle; a plain provider extension must not match.
270
+ const rivalGates = exists(shipGatePi) ? otherGateBundles(piExtDir, 'enforce-rules') : [];
271
+ const dshGate = path.join(home, '.dsh', 'plugins', 'agent-config-gates');
272
+ const bridgePolicy = path.join(home, '.config', 'agent-config-bridge', 'gate-policy.json');
273
+
274
+ const bridgePolicyMode = (() => {
275
+ const parsed = readJson(bridgePolicy);
276
+ return parsed && !parsed.__malformed ? (parsed.config?.destructive_mode ?? 'unknown') : 'unknown';
277
+ })();
278
+
279
+ return {
280
+ bridgePiGate: rivalGates[0] ?? null,
281
+ rivalGates,
282
+ shipGatePi: exists(shipGatePi) ? shipGatePi : null,
283
+ bridgeDshGate: exists(dshGate) && isGateBundle(dshGate) ? dshGate : null,
284
+ bridgePolicy: exists(bridgePolicy) ? bridgePolicy : null,
285
+ bridgePolicyMode,
286
+ dshMounted: scanDshMounts(path.join(home, '.dsh', 'profiles')),
287
+ };
288
+ }
@@ -0,0 +1,31 @@
1
+ const colorEnabled = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
2
+
3
+ const paint = (code, text) => (colorEnabled ? `\u001b[${code}m${text}\u001b[0m` : String(text));
4
+
5
+ export const c = {
6
+ bold: (s) => paint('1', s),
7
+ dim: (s) => paint('2', s),
8
+ green: (s) => paint('32', s),
9
+ yellow: (s) => paint('33', s),
10
+ red: (s) => paint('31', s),
11
+ cyan: (s) => paint('36', s),
12
+ };
13
+
14
+ export const log = {
15
+ plain: (...args) => console.log(...args),
16
+ info: (msg) => console.log(msg),
17
+ ok: (msg) => console.log(`${c.green('✔')} ${msg}`),
18
+ warn: (msg) => console.log(`${c.yellow('▲')} ${msg}`),
19
+ err: (msg) => console.error(`${c.red('✖')} ${msg}`),
20
+ step: (msg) => console.log(`${c.cyan('▸')} ${msg}`),
21
+ title: (msg) => console.log(`\n${c.bold(msg)}`),
22
+ };
23
+
24
+ export function table(rows, headers) {
25
+ if (rows.length === 0) return '';
26
+ const all = [headers, ...rows];
27
+ const widths = headers.map((_, i) => Math.max(...all.map((r) => String(r[i] ?? '').length)));
28
+ return all
29
+ .map((row) => row.map((cell, i) => String(cell ?? '').padEnd(widths[i])).join(' ').trimEnd())
30
+ .join('\n');
31
+ }
@@ -0,0 +1,347 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { packageRoot } from '../version.mjs';
5
+ import { backupOnce, copyTree, exists, hashFile, listDir, readText, removeDir, today } from './fsx.mjs';
6
+ import { stateDir } from './state.mjs';
7
+
8
+ /** Agent Skills spec limits — the same thresholds pi enforces on load. */
9
+ export const SKILL_NAME_MAX = 64;
10
+ export const SKILL_DESCRIPTION_MAX = 1024;
11
+ const SKILL_NAME_RE = /^[a-z0-9-]+$/;
12
+
13
+ export function skillsSource() {
14
+ return path.join(packageRoot(), 'skills');
15
+ }
16
+
17
+ export function commandsSource() {
18
+ return path.join(packageRoot(), 'commands');
19
+ }
20
+
21
+ export function agentsSource() {
22
+ return path.join(packageRoot(), 'agents');
23
+ }
24
+
25
+ /**
26
+ * Every skill directory carrying a SKILL.md is distributable — the 5
27
+ * shipgate-* gate skills plus the 22 full-dev lifecycle skills shipped here.
28
+ * Discovered from disk so adding a skill never needs a code change.
29
+ */
30
+ export function listSkillNames() {
31
+ return listDir(skillsSource())
32
+ .filter((entry) => entry.isDirectory() && exists(path.join(skillsSource(), entry.name, 'SKILL.md')))
33
+ .map((entry) => entry.name)
34
+ .sort();
35
+ }
36
+
37
+ export function listCommandNames() {
38
+ return listDir(commandsSource())
39
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
40
+ .map((entry) => entry.name)
41
+ .sort();
42
+ }
43
+
44
+ export function listAgentNames() {
45
+ return listDir(agentsSource())
46
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
47
+ .map((entry) => entry.name)
48
+ .sort();
49
+ }
50
+
51
+ /**
52
+ * Legacy installs copied a skill as a flat `<name>.md`; the current layout is
53
+ * `<name>/SKILL.md`. When both exist, the same skill `name:` is declared twice —
54
+ * harnesses then load it twice or pick a stale copy, and which one wins is not
55
+ * something the user can see. Report it; never delete (the flat file may be the
56
+ * user's own hand-written copy).
57
+ */
58
+ export function detectFlatSkillDuplicates(dir) {
59
+ if (!dir) return [];
60
+ const entries = listDir(dir);
61
+ const dirSkillNames = new Set(
62
+ entries
63
+ .filter((entry) => entry.isDirectory() && exists(path.join(dir, entry.name, 'SKILL.md')))
64
+ .map((entry) => entry.name),
65
+ );
66
+ return entries
67
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
68
+ .map((entry) => entry.name.slice(0, -3))
69
+ .filter((name) => dirSkillNames.has(name))
70
+ .sort();
71
+ }
72
+
73
+ /**
74
+ * Where a cleanup may park what it moves out of a skills root.
75
+ *
76
+ * It must not be a child of the root: every `.md` inside a root is a skill
77
+ * candidate. When such a directory is loaded as a skill path, pi names each of
78
+ * its flat files after the parent directory (`name = frontmatter.name ??
79
+ * parentDirName`), so parking the old flat skills in `<root>/_flat-backup`
80
+ * re-registers them — and a re-registered flat file collides with, and wins
81
+ * over, the real `<name>/SKILL.md`. Keeping the backup outside the root makes
82
+ * that impossible for every harness at once.
83
+ */
84
+ export function skillsBackupDir(kind, date = today()) {
85
+ return path.join(stateDir(), 'backups', `${kind}-${date}`);
86
+ }
87
+
88
+ /**
89
+ * Frontmatter reader for the two fields the spec constrains. Deliberately
90
+ * minimal: no dependency, no nested-map support, block scalars (`|`, `>`) are
91
+ * joined the way a loader would see them so a length check is not fooled by a
92
+ * wrapped description.
93
+ */
94
+ export function parseSkillFrontmatter(text) {
95
+ const block = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
96
+ if (!block) return {};
97
+ const lines = block[1].split(/\r?\n/);
98
+ const fields = {};
99
+ for (let i = 0; i < lines.length; i += 1) {
100
+ const hit = /^([A-Za-z0-9_-]+):[ \t]*(.*)$/.exec(lines[i]);
101
+ if (!hit) continue;
102
+ let value = hit[2].trim();
103
+ if (/^[|>][-+]?\d*$/.test(value)) {
104
+ const body = [];
105
+ while (i + 1 < lines.length && /^\s+\S/.test(lines[i + 1])) body.push(lines[++i].trim());
106
+ value = value.startsWith('|') ? body.join('\n') : body.join(' ');
107
+ }
108
+ fields[hit[1]] = value.replace(/^(['"])([\s\S]*)\1$/, '$2');
109
+ }
110
+ return fields;
111
+ }
112
+
113
+ /** Same accept/reject rules as the Agent Skills spec, in operator wording. */
114
+ export function validateSkillName(name) {
115
+ if (typeof name !== 'string' || name === '') return ['name 缺失'];
116
+ const issues = [];
117
+ if (name.length > SKILL_NAME_MAX) issues.push(`name 超过 ${SKILL_NAME_MAX} 字符(${name.length})`);
118
+ if (!SKILL_NAME_RE.test(name)) issues.push('name 只能含 a-z、0-9、-(当前有其他字符)');
119
+ if (/^-|-$/.test(name)) issues.push('name 不能以 - 开头或结尾');
120
+ if (name.includes('--')) issues.push('name 不能含连续 --');
121
+ return issues;
122
+ }
123
+
124
+ /**
125
+ * Audit one skill root the way a loader walks it: a directory holding SKILL.md
126
+ * is a skill and is not descended into; only the root's *direct* .md children
127
+ * count as flat skills (that is what `includeRootFiles` means on load); `.`
128
+ * prefixed entries are skipped. Every finding is report-only.
129
+ */
130
+ export function auditSkillRoot(root) {
131
+ const result = { root, skills: 0, invalidNames: [], longDescriptions: [], collisions: [], strayDirs: [] };
132
+ if (!root || !exists(root)) return result;
133
+ const claimed = new Map();
134
+
135
+ const register = (dir, file) => {
136
+ const front = parseSkillFrontmatter(readText(file));
137
+ const declared = path.basename(file) === 'SKILL.md';
138
+ const name = typeof front.name === 'string' && front.name !== '' ? front.name : path.basename(dir);
139
+ const description = typeof front.description === 'string' ? front.description.trim() : '';
140
+ // A flat file without a description is not loaded at all, so it is not a
141
+ // skill and must not be reported as one.
142
+ if (!declared && description === '') return;
143
+ result.skills += 1;
144
+ const nameIssues = validateSkillName(name);
145
+ if (nameIssues.length) result.invalidNames.push({ name, file, messages: nameIssues });
146
+ if (description.length > SKILL_DESCRIPTION_MAX) {
147
+ result.longDescriptions.push({ file, length: description.length });
148
+ }
149
+ const owners = claimed.get(name) ?? [];
150
+ owners.push(file);
151
+ claimed.set(name, owners);
152
+ };
153
+
154
+ const walk = (dir, includeFlat) => {
155
+ const entries = listDir(dir);
156
+ if (entries.some((entry) => entry.name === 'SKILL.md' && entry.isFile())) {
157
+ register(dir, path.join(dir, 'SKILL.md'));
158
+ return;
159
+ }
160
+ for (const entry of entries) {
161
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
162
+ const full = path.join(dir, entry.name);
163
+ let isDir = entry.isDirectory();
164
+ if (entry.isSymbolicLink()) {
165
+ try {
166
+ isDir = fs.statSync(full).isDirectory();
167
+ } catch {
168
+ continue;
169
+ }
170
+ }
171
+ if (isDir) walk(full, false);
172
+ else if (includeFlat && entry.name.endsWith('.md')) register(dir, full);
173
+ }
174
+ };
175
+
176
+ walk(root, true);
177
+
178
+ for (const [name, owners] of claimed) {
179
+ if (owners.length > 1) result.collisions.push({ name, winner: owners[0], losers: owners.slice(1) });
180
+ }
181
+
182
+ // A child directory with .md files but no SKILL.md is the shape a backup
183
+ // folder takes. It is inert until something passes it as a skill path, and
184
+ // then its files become skills under the directory's name — a silent trap.
185
+ for (const entry of listDir(root)) {
186
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
187
+ const dir = path.join(root, entry.name);
188
+ if (exists(path.join(dir, 'SKILL.md'))) continue;
189
+ const mdCount = listDir(dir).filter((child) => child.isFile() && child.name.endsWith('.md')).length;
190
+ if (mdCount > 0) result.strayDirs.push({ dir, mdCount });
191
+ }
192
+
193
+ return result;
194
+ }
195
+
196
+ function copyFile(src, dest, { dryRun }) {
197
+ if (dryRun) return;
198
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
199
+ // Overwriting a file the user already had (e.g. a hand-copied command) is
200
+ // still a destructive act: keep one backup per day before replacing it.
201
+ if (fs.existsSync(dest)) backupOnce(dest);
202
+ fs.copyFileSync(src, dest);
203
+ }
204
+
205
+ function installFileSet(files, srcDir, destDir, recordKey, record, { dryRun }) {
206
+ const result = { installed: [], skipped: [], overwritten: [] };
207
+ record[recordKey] ??= {};
208
+ for (const file of files) {
209
+ const src = path.join(srcDir, file);
210
+ const dest = path.join(destDir, file);
211
+ const hash = hashFile(src);
212
+ if (record[recordKey][file]?.hash === hash && exists(dest)) {
213
+ result.skipped.push(file);
214
+ continue;
215
+ }
216
+ // The file exists but was not put there by ShipGate (no manifest record):
217
+ // it is the user's own copy. Overwriting is reasonable for a shared skill
218
+ // pack, but it must never be silent.
219
+ if (exists(dest) && !record[recordKey][file]) result.overwritten.push(file);
220
+ copyFile(src, dest, { dryRun });
221
+ if (!dryRun) record[recordKey][file] = { hash, installedAt: new Date().toISOString() };
222
+ result.installed.push(file);
223
+ }
224
+ return result;
225
+ }
226
+
227
+ /**
228
+ * Digest of a whole skill directory.
229
+ *
230
+ * A skill ships more than its entry file: `scripts/`, `references/`, templates.
231
+ * Hashing only SKILL.md froze those at first install — a fixed script never
232
+ * reached any harness, and `install` reported "no change" while the copies were
233
+ * stale. The digest covers relative path + content for every regular file, in a
234
+ * sorted order so it does not depend on directory iteration.
235
+ */
236
+ export function hashTree(dir) {
237
+ const entries = [];
238
+ const walk = (current, prefix) => {
239
+ for (const entry of listDir(current)) {
240
+ const full = path.join(current, entry.name);
241
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
242
+ if (entry.isDirectory()) {
243
+ walk(full, rel);
244
+ continue;
245
+ }
246
+ if (!entry.isFile()) continue;
247
+ entries.push(`${rel}\u0000${hashFile(full)}`);
248
+ }
249
+ };
250
+ walk(dir, '');
251
+ entries.sort();
252
+ return crypto.createHash('sha256').update(entries.join('\n')).digest('hex');
253
+ }
254
+
255
+ /**
256
+ * Is any source file missing or different in the destination?
257
+ *
258
+ * Only the source's file set is compared: a harness skill directory may carry
259
+ * files a user put there (extra notes, a local asset), and treating those as
260
+ * drift would make every install a "change". What this does catch is the case
261
+ * that matters — a tampered or half-copied skill is repaired on the next run.
262
+ */
263
+ export function sourceTreeDrift(srcDir, destDir) {
264
+ let drift = false;
265
+ const walk = (src, dest, prefix) => {
266
+ for (const entry of listDir(src)) {
267
+ const from = path.join(src, entry.name);
268
+ const to = path.join(dest, entry.name);
269
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
270
+ if (entry.isDirectory()) {
271
+ walk(from, to, rel);
272
+ continue;
273
+ }
274
+ if (!entry.isFile()) continue;
275
+ if (!exists(to) || hashFile(to) !== hashFile(from)) drift = true;
276
+ }
277
+ };
278
+ walk(srcDir, destDir, '');
279
+ return drift;
280
+ }
281
+
282
+ /**
283
+ * Copy-on-change: a skill whose directory digest already matches the manifest is
284
+ * skipped, so re-running install does not touch mtimes or churn backups.
285
+ */
286
+ export function installSkills(harness, record, { dryRun = false } = {}) {
287
+ const result = { installed: [], skipped: [] };
288
+ if (!harness.skillsPath) return result;
289
+ // A link whose target is gone cannot be written through. Creating the link is
290
+ // agent-config-bridge's job, so fail-closed and name the owner instead of
291
+ // silently replacing the link with a copy (which would fork the skill set).
292
+ if (harness.skillsBroken) {
293
+ throw new Error(
294
+ `skills 链接已断开:${harness.skillsDeclaredPath}(目标不存在)。` +
295
+ `请在 agent-config-bridge 中重新 adopt ${harness.id} 以重建链接,或先删除该链接再重试。`,
296
+ );
297
+ }
298
+ record.skills ??= {};
299
+
300
+ for (const name of listSkillNames()) {
301
+ const srcDir = path.join(skillsSource(), name);
302
+ const destDir = path.join(harness.skillsPath, name);
303
+ const hash = hashTree(srcDir);
304
+
305
+ if (record.skills[name]?.hash === hash && exists(path.join(destDir, 'SKILL.md')) && !sourceTreeDrift(srcDir, destDir)) {
306
+ result.skipped.push(name);
307
+ continue;
308
+ }
309
+ if (!dryRun) {
310
+ const destSkill = path.join(destDir, 'SKILL.md');
311
+ if (exists(destSkill)) backupOnce(destSkill);
312
+ copyTree(srcDir, destDir);
313
+ record.skills[name] = { hash, installedAt: new Date().toISOString() };
314
+ }
315
+ result.installed.push(name);
316
+ }
317
+ return result;
318
+ }
319
+
320
+ export function installCommands(harness, record, { dryRun = false } = {}) {
321
+ if (!harness.commandsPath) return { installed: [], skipped: [], skippedReason: 'harness 无 commands 目录' };
322
+ return installFileSet(listCommandNames(), commandsSource(), harness.commandsPath, 'commands', record, { dryRun });
323
+ }
324
+
325
+ export function installAgents(harness, record, { dryRun = false } = {}) {
326
+ if (!harness.agentsPath) return { installed: [], skipped: [], skippedReason: 'harness 无 agents 目录' };
327
+ return installFileSet(listAgentNames(), agentsSource(), harness.agentsPath, 'agents', record, { dryRun });
328
+ }
329
+
330
+ /**
331
+ * --prune only removes directories this manifest recorded whose skill no longer
332
+ * exists in the package; user-authored skills in the same folder are untouched.
333
+ */
334
+ export function pruneSkills(harness, record, { dryRun = false } = {}) {
335
+ const removed = [];
336
+ if (!harness.skillsPath) return removed;
337
+ const shipped = new Set(listSkillNames());
338
+
339
+ for (const name of Object.keys(record.skills ?? {})) {
340
+ if (shipped.has(name)) continue;
341
+ const dest = path.join(harness.skillsPath, name);
342
+ if (exists(dest) && !dryRun) removeDir(dest);
343
+ delete record.skills[name];
344
+ removed.push(name);
345
+ }
346
+ return removed;
347
+ }