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,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
+ }
@@ -0,0 +1,50 @@
1
+ import path from 'node:path';
2
+ import { HOME } from './cfg.mjs';
3
+ import { readIfExists, writeText } from './fsx.mjs';
4
+
5
+ /**
6
+ * ShipGate's own configuration root.
7
+ *
8
+ * `SHIPGATE_STATE_DIR` exists so a test or a drill can point the CLI at a
9
+ * throwaway directory instead of the live policy. Without it, a test of
10
+ * `policy --mode` would switch the real gate - the one thing a test must never
11
+ * do. Unset means the normal per-user location.
12
+ */
13
+ export function stateDir() {
14
+ const override = process.env.SHIPGATE_STATE_DIR;
15
+ return override ? path.resolve(override) : path.join(HOME, '.config', 'shipgate');
16
+ }
17
+
18
+ export function manifestPath() {
19
+ return path.join(stateDir(), 'manifest.json');
20
+ }
21
+
22
+ export function cacheDir() {
23
+ return path.join(HOME, '.cache', 'shipgate');
24
+ }
25
+
26
+ const EMPTY = { version: 1, harnesses: {} };
27
+
28
+ export function loadManifest() {
29
+ const text = readIfExists(manifestPath());
30
+ if (text === null) return structuredClone(EMPTY);
31
+ try {
32
+ const parsed = JSON.parse(text);
33
+ return { ...structuredClone(EMPTY), ...parsed, harnesses: parsed.harnesses ?? {} };
34
+ } catch (error) {
35
+ throw new Error(`manifest 损坏,请检查 ${manifestPath()}:${error.message}`);
36
+ }
37
+ }
38
+
39
+ export function saveManifest(manifest) {
40
+ writeText(manifestPath(), JSON.stringify(manifest, null, 2) + '\n');
41
+ }
42
+
43
+ export function harnessRecord(manifest, id) {
44
+ return manifest.harnesses[id];
45
+ }
46
+
47
+ export function ensureHarnessRecord(manifest, id) {
48
+ manifest.harnesses[id] ??= { managed: false, skills: {}, inject: null, gate: null };
49
+ return manifest.harnesses[id];
50
+ }
@@ -0,0 +1,67 @@
1
+ import path from 'node:path';
2
+ import { cacheDir } from './state.mjs';
3
+ import { readIfExists, today, writeText } from './fsx.mjs';
4
+ import { run } from './exec.mjs';
5
+ import { VERSION } from '../version.mjs';
6
+
7
+ const PACKAGE = 'shipgate-cli';
8
+ const REGISTRY = `https://registry.npmjs.org/${PACKAGE}/latest`;
9
+
10
+ function stampPath() {
11
+ return path.join(cacheDir(), 'last-update-check');
12
+ }
13
+
14
+ export function checkedToday() {
15
+ return readIfExists(stampPath())?.trim() === today();
16
+ }
17
+
18
+ export function markChecked() {
19
+ writeText(stampPath(), today() + '\n');
20
+ }
21
+
22
+ export function compareVersions(a, b) {
23
+ const pa = String(a).split('.').map((n) => Number.parseInt(n, 10) || 0);
24
+ const pb = String(b).split('.').map((n) => Number.parseInt(n, 10) || 0);
25
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
26
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
27
+ if (diff !== 0) return diff > 0 ? 1 : -1;
28
+ }
29
+ return 0;
30
+ }
31
+
32
+ /**
33
+ * Network failure is reported, never thrown: `doctor` and the daily check must
34
+ * work offline.
35
+ */
36
+ export async function checkLatest({ timeoutMs = 6000 } = {}) {
37
+ const controller = new AbortController();
38
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
39
+ try {
40
+ const response = await fetch(REGISTRY, {
41
+ signal: controller.signal,
42
+ headers: { accept: 'application/json' },
43
+ });
44
+ if (!response.ok) return { ok: false, error: `HTTP ${response.status}` };
45
+ const data = await response.json();
46
+ const latest = data.version;
47
+ if (!latest) return { ok: false, error: '响应里没有 version' };
48
+ return { ok: true, latest, current: VERSION, outdated: compareVersions(latest, VERSION) > 0 };
49
+ } catch (error) {
50
+ return { ok: false, error: error.name === 'AbortError' ? `超时 ${timeoutMs}ms` : error.message };
51
+ } finally {
52
+ clearTimeout(timer);
53
+ }
54
+ }
55
+
56
+ export function selfUpdate() {
57
+ const result = run('npm', ['i', '-g', `${PACKAGE}@latest`], { timeout: 900_000 });
58
+ return { ok: result.ok, code: result.code, stderr: result.stderr.slice(0, 4000), stdout: result.stdout.slice(-2000) };
59
+ }
60
+
61
+ export function installHint() {
62
+ return `npm i -g ${PACKAGE}`;
63
+ }
64
+
65
+ export function updateHint() {
66
+ return `shipgate update # 全局 ${PACKAGE}`;
67
+ }
@@ -0,0 +1,14 @@
1
+ import fs from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
5
+
6
+ export const VERSION = pkg.version;
7
+ export const NAME = pkg.name;
8
+ export const REPO = pkg.repository?.url?.replace(/^git\+/, '').replace(/\.git$/, '') ?? '';
9
+
10
+ export function packageRoot() {
11
+ // fileURLToPath, not URL.pathname: on Windows the latter yields "/E:/repo/...",
12
+ // and path.resolve() then prepends the current drive, producing "E:\E:\repo".
13
+ return fileURLToPath(new URL('..', import.meta.url));
14
+ }
@@ -0,0 +1,82 @@
1
+ <!-- shipgate:begin v3 -->
2
+ ## ShipGate 闸链(`shipgate install` 维护的托管区块,勿手改区块内内容)
3
+
4
+ 本机部署了 ShipGate {{VERSION}}:27 个开发 skill + 4 道闸 + 按 harness 分级的门控。
5
+
6
+ ### 一件事先记住:先立契约,再写代码
7
+
8
+ 任何非琐碎改动,先走 `ai-spec` skill 生成 `tasks/CHG-<id>/{PRD,SPEC,TRACEABILITY}.md`,再用 `shipgate spec check` 验证契约成立。没有契约的改动不算完成。
9
+
10
+ ### 四道闸与触发时机
11
+
12
+ | 闸 | 什么时候过 | 命令 | 对应 skill |
13
+ |---|---|---|---|
14
+ | spec | 任何代码改动之前 | `shipgate spec check` | `ai-spec` / `shipgate-spec` |
15
+ | quality | 每次编辑后 / 提交前 | `shipgate quality` | `shipgate-quality` |
16
+ | security | 提交前 / 发布前(必须显式给范围) | `shipgate security --scope <scope.md>` | `shipgate-security` |
17
+ | ship | 装 / 升级 / 换 harness 后 | `shipgate status` | `shipgate-install` |
18
+
19
+ ### 全周期技能入口(按阶段找 skill)
20
+
21
+ | 阶段 | 用哪个 skill |
22
+ |---|---|
23
+ | 需求模糊 | `intent-grill` |
24
+ | 项目没基线 | `project-health-audit` |
25
+ | 写 PRD | `prd` |
26
+ | 工程契约 | `ai-spec` |
27
+ | 实现 | `goal-driven-development`(或用 `/ralph`、`/ralph-yolo` 循环) |
28
+ | 调试 | `code-debugger` / `debug-ui` |
29
+ | 审查 | `code-review` / `security-audit` / `ux-experience-audit` |
30
+ | 迭代与收尾 | `iteration-manager` / `nodejs-npm-auto-release` |
31
+ | 宿主环境初始化 | `dev-host-init` |
32
+ | 复盘找可复用流程 | `discover-skill-opportunities` |
33
+
34
+ ### 门控分级(重要,别误判)
35
+
36
+ - **硬拦截**(进程级):`pi`、`dsh` 等自由度高的 harness —— 装了 `enforce-rules` 扩展,破坏性命令、跳层直读会被真的拦下。
37
+ - **软约束**(靠 skill + 本文档):`claude`、`codex`、`gemini`、`cursor`、`kimi`、`antigravity` —— 这些 harness 没有对应 hook 面,ShipGate 不会假装它们有硬门控;改代码质量靠 `shipgate quality` 可验证。
38
+
39
+ ### 硬门控策略(仅 pi / dsh 生效)
40
+
41
+ ```bash
42
+ shipgate policy # 看当前 policy 与受保护工作区
43
+ shipgate policy --add-protected <dir>
44
+ shipgate policy --mode enforce|bypass
45
+ ```
46
+
47
+ 受保护工作区里的 `git stash/reset --hard/clean -f/checkout -- .` 等清场命令会被拦下;需要临时放宽用 `--mode bypass` 并说明原因。
48
+
49
+ ### 引擎:slop 检测(aislop)与安全审计(cbh)
50
+
51
+ 两者都是闸的依赖,装在 PATH 上一次,所有 harness 的 shell 共用;缺了闸返回退出码 3,`shipgate doctor` 会给安装命令。
52
+
53
+ ```bash
54
+ npm i -g aislop # quality 闸
55
+ git clone --depth 1 https://github.com/elementalsouls/Claude-BugHunter ~/.local/src/Claude-BugHunter
56
+ python3 -m pip install --user -i https://pypi.org/simple ~/.local/src/Claude-BugHunter # 无 pipx 走这两步
57
+ # Windows PowerShell 路径写 "$HOME\.local\src\Claude-BugHunter",python3 换 python;有 pipx 可 pipx install git+…
58
+ aislop doctor && cbh --help # 自检:aislop 四引擎应全 ready;cbh 无 --version,看子命令
59
+ ```
60
+
61
+ 什么时候调谁:
62
+
63
+ | 目的 | 命令 |
64
+ |---|---|
65
+ | 判定这次改动能不能提交 | `shipgate quality`(阈值与 error 级判定都在闸里) |
66
+ | 看具体哪些行是 slop / 机械修复 | `aislop scan . -d` → `aislop fix` → 结构性大改 `aislop agent` |
67
+ | 安全:先确认授权范围 | `shipgate security --scope <scope.md>`(只校验,不发包) |
68
+ | 安全:范围内侦察 / 归类 / 验证 | `cbh recon / surface / diff / classify / triage`,方法论按 `shipgate-security` skill |
69
+
70
+ `cbh` 自带的 82 个 `hunt-*` skill **默认未装**(体积与迭代频率不合,不随 ShipGate 分发)。需要时自行安装:`pwsh scripts/install.ps1 -All`(装进 `~/.claude/skills`,备份落在加载路径之外),再按 `cbh classify` 指到的 skill 名去读。
71
+
72
+ 调试走 `code-debugger` / `debug-ui` skill,纯提示词、不需要额外引擎。
73
+
74
+ ### 硬规则
75
+
76
+ 1. `quality` 不通过(score < {{MIN}} 或有 error 级发现)→ 先 `aislop fix`,不许带病提交。
77
+ 2. `security` 没有 `--scope` 会被拒绝(退出码 2);主动探测永不自动执行。
78
+ 3. `spec` 不通过 → 补契约三件套,不许先写代码后补文档。
79
+ 4. 排查入口:`shipgate doctor`;不知道怎么走就问 `shipgate gates`。
80
+ 5. 引擎缺失不是绕过的理由:`shipgate doctor` 给安装命令;不要用「我手动看过了」代替 quality / security 闸。
81
+
82
+ <!-- shipgate:end -->
@@ -0,0 +1,119 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "title": "Developer Profile",
4
+ "description": "Structured output from /dev-env-scan — environment capabilities and developer preferences",
5
+ "type": "object",
6
+ "properties": {
7
+ "$schema": {
8
+ "type": "string",
9
+ "const": "dev-profile/v1"
10
+ },
11
+ "generated_at": {
12
+ "type": "string",
13
+ "format": "date-time",
14
+ "description": "ISO 8601 timestamp of when this profile was generated"
15
+ },
16
+ "environment": {
17
+ "type": "object",
18
+ "properties": {
19
+ "os": {
20
+ "type": "object",
21
+ "properties": {
22
+ "name": {"type": "string"},
23
+ "version": {"type": "string"},
24
+ "arch": {"type": "string", "enum": ["x64", "arm64", "x86"]}
25
+ },
26
+ "required": ["name", "version", "arch"]
27
+ },
28
+ "shell": {"type": "string"},
29
+ "languages": {
30
+ "type": "object",
31
+ "additionalProperties": {
32
+ "oneOf": [
33
+ {"type": "null"},
34
+ {
35
+ "type": "object",
36
+ "properties": {
37
+ "version": {"type": "string"},
38
+ "managers": {
39
+ "type": "array",
40
+ "items": {"type": "string"}
41
+ }
42
+ },
43
+ "required": ["version"]
44
+ }
45
+ ]
46
+ }
47
+ },
48
+ "gpu": {
49
+ "oneOf": [
50
+ {"type": "null"},
51
+ {
52
+ "type": "object",
53
+ "properties": {
54
+ "vendor": {"type": "string", "enum": ["nvidia", "amd", "intel", "apple"]},
55
+ "model": {"type": "string"},
56
+ "vram_gb": {"type": "number"},
57
+ "cuda": {"type": ["string", "null"]}
58
+ },
59
+ "required": ["vendor", "model"]
60
+ }
61
+ ]
62
+ },
63
+ "docker": {"type": "boolean"},
64
+ "memory_gb": {"type": "number"},
65
+ "disk_free_gb": {
66
+ "type": "object",
67
+ "additionalProperties": {"type": "number"}
68
+ }
69
+ },
70
+ "required": ["os", "shell", "languages"]
71
+ },
72
+ "preferences": {
73
+ "type": "object",
74
+ "properties": {
75
+ "primary_languages": {
76
+ "type": "array",
77
+ "items": {"type": "string"},
78
+ "description": "User's preferred languages for this project"
79
+ },
80
+ "package_managers": {
81
+ "type": "object",
82
+ "additionalProperties": {"type": "string"},
83
+ "description": "Preferred package manager per language ecosystem"
84
+ },
85
+ "deployment": {
86
+ "type": "string",
87
+ "enum": ["docker", "bare-metal", "serverless", "paas", "uv", "conda"],
88
+ "description": "Preferred deployment style"
89
+ },
90
+ "testing": {
91
+ "type": "string",
92
+ "description": "Testing philosophy: tdd, coverage-NN, post-impl, minimal"
93
+ },
94
+ "ci": {
95
+ "type": "string",
96
+ "enum": ["github-actions", "gitlab-ci", "jenkins", "local", "none"],
97
+ "description": "CI/CD platform preference"
98
+ },
99
+ "style_enforcement": {
100
+ "type": "string",
101
+ "enum": ["strict", "moderate", "minimal"],
102
+ "description": "How strictly to enforce code style"
103
+ },
104
+ "repo_style": {
105
+ "type": "string",
106
+ "enum": ["monorepo", "polyrepo"],
107
+ "description": "Repository organization preference"
108
+ }
109
+ },
110
+ "required": ["primary_languages"]
111
+ },
112
+ "constraints": {
113
+ "type": "array",
114
+ "items": {"type": "string"},
115
+ "description": "Special constraints: offline, air-gapped, compliance, etc."
116
+ }
117
+ },
118
+ "required": ["$schema", "generated_at", "environment", "preferences"]
119
+ }