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,226 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ dev-host-init 占位符填充器(跨平台,零本机硬编码)
5
+ ===================================================
6
+ 核心职责:
7
+ 1. 运行 host-scan(Linux/macOS/WSL → host-scan.sh;Windows → host-scan.ps1)
8
+ 2. 把 host-injection.template.md 的 {{占位符}} 替换为「探测到的本机值」或「明确兜底文案」
9
+ 3. 两道门禁:渲染产物 0 未替换占位符;模板 0 敏感硬编码
10
+
11
+ 安全原则:
12
+ - 本脚本必须保持「通用」:不出现任何真实 IP / 域名 / 用户名 / 端口 / 绝对路径。
13
+ 所有判定都基于 host-scan JSON 里 *探测到* 的值,或通用正则黑名单(匹配模式而非具体值)。
14
+ - 模板是开源共享的:只能含 {{占位符}};真实值一律由 init 探测回填。
15
+ - 探测不到 → 输出「未检测到」,绝不猜一个本机专属值。
16
+ """
17
+ import argparse
18
+ import json
19
+ import os
20
+ import re
21
+ import subprocess
22
+ import sys
23
+
24
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
25
+
26
+ # ---------- 敏感模式黑名单(通用正则,不写死具体 IP/域名/用户名/端口)----------
27
+ SENSITIVE_PATTERNS = [
28
+ r"(?<![\d.])\b(?!(?:127\.0\.0\.1|0\.0\.0\.0|::1)\b)(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", # 任意公网/内网 IPv4(豁免回环示例)
29
+ r"https?://[a-z0-9][a-z0-9.-]*\.[a-z]{2,}", # 任意公网域名 URL
30
+ r"\b[A-Za-z0-9-]+\.(?:com|net|cn|org|io|dev|app|pro)\b", # 域名根
31
+ r"/home/[a-z_][a-z0-9_]*", # Linux 用户绝对路径
32
+ r"C:\\Users\\(?!<user>)", # Windows 用户绝对路径(豁免 <user> 占位示例)
33
+ r"\b[A-Z0-9]{20}\b", # 类 API Key(20 位大写混搭)
34
+ r"(api[_-]?key|secret|token|password|passwd)\s*[:=]\s*['\"]?[^\s'\"]{8,}", # 凭据赋值
35
+ r"-----BEGIN (?:RSA|OPENSSH|EC|DSA) PRIVATE KEY-----", # 私钥头
36
+ ]
37
+
38
+ def run_host_scan():
39
+ """跨平台跑 host-scan;失败返回 {}(渲染端靠兜底文案继续)"""
40
+ sh = os.path.join(SCRIPT_DIR, "host-scan.sh")
41
+ ps1 = os.path.join(SCRIPT_DIR, "host-scan.ps1")
42
+ if os.name == "nt":
43
+ # Windows 原生:优先 PowerShell 探测(Git Bash 下跑 .sh 会因缺 WSL/Linux 工具输出空 JSON)
44
+ if os.path.exists(ps1):
45
+ try:
46
+ out = subprocess.run(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", ps1],
47
+ capture_output=True, text=True, timeout=90)
48
+ return json.loads(out.stdout) if out.returncode == 0 else {}
49
+ except Exception:
50
+ return {}
51
+ else:
52
+ # Linux / macOS / WSL:优先 bash 脚本
53
+ if os.path.exists(sh):
54
+ try:
55
+ out = subprocess.run(["bash", sh], capture_output=True, text=True, timeout=90)
56
+ return json.loads(out.stdout) if out.returncode == 0 else {}
57
+ except Exception:
58
+ return {}
59
+ return {}
60
+
61
+ def detect_value(h, key, default=None):
62
+ cur = h
63
+ for part in key.split("."):
64
+ if isinstance(cur, dict) and part in cur:
65
+ cur = cur[part]
66
+ else:
67
+ return default
68
+ return cur if cur is not None else default
69
+
70
+ def pick(ports, candidates):
71
+ """从探测到的端口列表里按优先级挑第一个在候选里的端口(端口号 int/str 均可)"""
72
+ strs = {str(p) for p in (ports or [])}
73
+ for c in candidates:
74
+ if str(c) in strs:
75
+ return str(c)
76
+ return ""
77
+
78
+ def build_values(h):
79
+ """全部值来自 host-scan 探测;无探测项 → '未检测到' 兜底文案"""
80
+ v = {}
81
+ net = h.get("network", {}) or {}
82
+ proxy = h.get("proxy", {}) or {}
83
+ ports = net.get("listen_ports", []) or []
84
+ open_ports = proxy.get("open_local_ports", []) or []
85
+ home = os.path.expanduser("~")
86
+
87
+ vps_ip = net.get("vps_ip", "") or ""
88
+ vps_alias = net.get("vps_alias", "") or ""
89
+ frp_svc = (net.get("frp_svc", "") or "").replace(".service", "")
90
+ ngx_name = net.get("nginx_server_name", "") or ""
91
+ if ngx_name in ("", "_", "example.com", "default_server"):
92
+ ngx_name = ""
93
+ ngx_port = net.get("nginx_port", "") or ""
94
+
95
+ # 公网 HTTPS 端口:优先 FRP 隧道端口,其次 nginx listen;端口必须真实探测到
96
+ pub_port = pick(ports, [int(ngx_port) if str(ngx_port).isdigit() else 0, 8443, 9443, 443])
97
+ pub_domain = ngx_name
98
+ ssh_local_port = pick(ports, [22022, 2222, 22])
99
+ d_port = pick(ports, [8090, 8000, 8080])
100
+ mcp_port = pick(ports, [8765, 8766, 8001])
101
+ mcp_ext = pick(ports, [8767, 8766, 8002])
102
+ rstudio = pick(ports, [8787, 8788, 8786])
103
+ tunnel = pick(ports, [8787, 8080, 8888])
104
+ http_p = pick(open_ports, [7890, 8080, 8888, 1080])
105
+ socks = pick(open_ports, [1080, 7890, 10808])
106
+
107
+ v["NET_VPS_IP_PUB"] = vps_ip or "未检测到(SSH config 无 HostName,请手填)"
108
+ v["NET_VPS_SSH_ALIAS"] = vps_alias or "未检测到(SSH config 无 Host,请手填)"
109
+ v["NET_PUB_DOMAIN"] = pub_domain or "未检测到(nginx 无 server_name,请手填)"
110
+ v["NET_PUB_PORT"] = pub_port or "未检测到(无公网 HTTPS 端口,请手填)"
111
+ v["NET_PUB_URL"] = f"https://{pub_domain}:{pub_port}" if pub_domain and pub_port else "未检测到(公网入口,请手填)"
112
+ v["NET_SSH_LOCAL_PORT"] = ssh_local_port or "未检测到(公网 SSH 端口在云控制台,请手填)"
113
+ v["NET_SSH_USER"] = os.environ.get("USER", os.environ.get("USERNAME", "未检测到"))
114
+ v["NET_SSH_METHOD"] = f"FutureTerminal / ssh -p {v['NET_SSH_LOCAL_PORT']}" if "未检测" not in v["NET_SSH_LOCAL_PORT"] else "未检测到(SSH 端口)"
115
+ v["NET_PORT_TUNNEL_CODESERVER"] = f"127.0.0.1:{tunnel}" if tunnel else "未检测到"
116
+ v["NET_PORT_RSTUDIO"] = rstudio or "未检测到"
117
+ v["NET_PORT_DASHBOARD"] = d_port or "未检测到"
118
+ v["NET_PORT_MCP"] = mcp_port or "未检测到"
119
+ v["NET_PORT_MCP_EXT"] = mcp_ext or "未检测到"
120
+ v["NET_FRP_SVC"] = frp_svc or "未检测到(无 frp systemd 服务)"
121
+ v["NET_FRP_BIND_PORT"] = "7000" # frp 默认;可按 frpc.toml 探测
122
+ v["NET_APP_SLUG"] = "未检测到(项目名,init 后自定义)"
123
+ v["NET_PROXY_HTTP"] = f"127.0.0.1:{http_p}" if http_p else "未检测到"
124
+ v["NET_PROXY_SOCKS5"] = f"127.0.0.1:{socks}" if socks else "未检测到"
125
+ v["NET_INGRESS_FILE"] = "未检测到(用户自建权威运维文档路径)"
126
+ v["NET_KAIROS_DOCS"] = "未检测到(用户自建 KAIROS 端点文档路径)"
127
+ v["NET_NGINX_CONF"] = "未检测到(用户自建 nginx 配置路径)"
128
+ v["NET_FRP_DIR"] = "未检测到(用户自建 frp 运维目录)"
129
+
130
+ # 通用占位符(环境/硬件,全探测驱动)
131
+ cpu = detect_value(h, "hardware.cpu_model", "")
132
+ ram = detect_value(h, "hardware.memory_gb", 0)
133
+ swap = detect_value(h, "hardware.swap_gb", 0)
134
+ gpu = detect_value(h, "hardware.gpu", None)
135
+ disks = detect_value(h, "hardware.disks", []) or []
136
+ storage_desc = " + ".join(
137
+ f"{d.get('mount','?')} {d.get('total_gb','?')}G(空{d.get('free_gb','?')}G)"
138
+ for d in disks if isinstance(d, dict)) or "未检测到"
139
+ gpu_desc = (f"{gpu.get('model','')} {gpu.get('vram_mb','')}MB"
140
+ if isinstance(gpu, dict) else ("无独立 GPU" if gpu is None else "未检测到"))
141
+
142
+ v["DEV_ROOT"] = os.path.join(home, "Development")
143
+ v["HOME_DIR"] = home
144
+ v["LANG_HEADER"] = "始终使用简体中文回复。"
145
+ v["CODEBASE_MCP_DOCS"] = os.path.join(home, "Development", "codebase-memory-mcp", "DEPLOYMENT.zh-CN.md")
146
+ v["OS_NAME"] = detect_value(h, "os.name", "Unknown")
147
+ v["CPU"] = cpu or "未检测到(lscpu 手查)"
148
+ v["RAM"] = f"{ram} GB" if ram else "未检测到"
149
+ v["SWAP"] = f"{swap} GB" if swap else "未检测到"
150
+ v["GPU"] = gpu_desc
151
+ v["STORAGE"] = storage_desc
152
+ v["HW_NOTES"] = "2026 dev-host-init 实测探测(host-scan)" if cpu else "未检测到,请手填"
153
+ v["PROXY_DESC"] = (f"本机代理:socks5 {v['NET_PROXY_SOCKS5']} / http {v['NET_PROXY_HTTP']}(init 探测)"
154
+ if "未检测" not in v["NET_PROXY_HTTP"] else "未检测到本地代理")
155
+ v["PROXY_SOCKS5"] = v["NET_PROXY_SOCKS5"]
156
+ v["PROXY_HTTP"] = v["NET_PROXY_HTTP"]
157
+ v["PROXY_HTTP_HOSTPORT"] = http_p or "未检测到"
158
+ v["MIRROR_LIST"] = "~/AGENTS.md、~/.claude/CLAUDE.md、~/.codex/AGENTS.md、~/.gemini/GEMINI.md"
159
+ v["REFERENCE_DIR"] = os.path.join(home, "agent-reference")
160
+ envs = detect_value(h, "env_managers.conda_envs", []) or []
161
+ uv_py = detect_value(h, "env_managers.uv_pythons", []) or []
162
+ if envs or uv_py:
163
+ v["ENV_TABLE"] = "conda: " + ", ".join(envs[:12]) + ("\nuv python: " + ", ".join(uv_py[:8]) if uv_py else "")
164
+ else:
165
+ v["ENV_TABLE"] = "未检测到 conda/uv 环境"
166
+ v["PREFERENCES_SUMMARY"] = "未采集偏好,走默认偏好模板"
167
+ return v
168
+
169
+ def fill_template(template_text, values):
170
+ out = template_text
171
+ for k, val in values.items():
172
+ out = out.replace("{{" + k + "}}", val)
173
+ # 兜底:仍残留 {{...}} → 明确文案(保证 0 占位符残留)
174
+ out = re.sub(r"\{\{[A-Z_]+\}\}", "[未提供,请手填]", out)
175
+ return out
176
+
177
+ def detect_sensitive(text):
178
+ """返回命中的通用敏感模式;空 = 通过"""
179
+ hits = []
180
+ for pat in SENSITIVE_PATTERNS:
181
+ if re.search(pat, text, re.IGNORECASE):
182
+ hits.append(pat)
183
+ return hits
184
+
185
+ def main():
186
+ ap = argparse.ArgumentParser()
187
+ ap.add_argument("--template", required=True)
188
+ ap.add_argument("--output", required=False)
189
+ ap.add_argument("--dry-run", action="store_true")
190
+ args = ap.parse_args()
191
+
192
+ tpl = open(args.template, encoding="utf-8").read()
193
+ tpl_hits = detect_sensitive(tpl)
194
+ if tpl_hits:
195
+ print(f"[FAIL] 模板含敏感硬编码: {tpl_hits}", file=sys.stderr)
196
+ sys.exit(2)
197
+ print(f"[OK] 模板敏感检查通过: {args.template}")
198
+
199
+ h = run_host_scan()
200
+ if not h:
201
+ print("[WARN] host-scan 探测失败,占位符走兜底文案", file=sys.stderr)
202
+
203
+ values = build_values(h)
204
+ out = fill_template(tpl, values)
205
+
206
+ leftover = re.findall(r"\{\{", out)
207
+ if leftover:
208
+ print(f"[FAIL] 渲染产物仍有 {len(leftover)} 处未替换占位符", file=sys.stderr)
209
+ sys.exit(3)
210
+
211
+ # 渲染产物敏感检查:本机产物允许探测回填,但须确认无「模板硬编码」来源
212
+ out_hits = detect_sensitive(out)
213
+ if out_hits:
214
+ print(f"[WARN] 渲染产物命中敏感模式: {out_hits}(本机探测合法;确认非模板硬编码)", file=sys.stderr)
215
+
216
+ print(f"[OK] 渲染完成,共替换 {len(values)} 个占位符")
217
+ if args.output:
218
+ os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
219
+ open(args.output, "w", encoding="utf-8").write(out)
220
+ print(f"[OK] 已写出: {args.output}")
221
+ else:
222
+ print(json.dumps({k: val for k, val in values.items() if k.startswith("NET_")},
223
+ ensure_ascii=False, indent=2))
224
+
225
+ if __name__ == "__main__":
226
+ main()
@@ -0,0 +1,159 @@
1
+ #Requires -Version 5.1
2
+ # dev-host-init: host environment detection (Windows native PowerShell)
3
+ # NOTE: runtime-verified on Windows only (dev environment has no pwsh).
4
+ # Outputs a single JSON object to stdout, same schema as host-scan.sh.
5
+ # Usage: powershell -NoProfile -ExecutionPolicy Bypass -File host-scan.ps1
6
+
7
+ [CmdletBinding()] param()
8
+ $ErrorActionPreference = 'SilentlyContinue'
9
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
10
+
11
+ function Test-Cmd($name) { [bool](Get-Command $name -ErrorAction SilentlyContinue) }
12
+ function Get-Ver($exe, $arg, $regex) {
13
+ if (-not (Test-Cmd $exe)) { return $null }
14
+ $out = & $exe $arg 2>$null | Select-Object -First 1
15
+ if ($out -and $out -match $regex) { return $Matches[1] }
16
+ return $null
17
+ }
18
+
19
+ # ---------- OS & shell ----------
20
+ $osName = "Windows"
21
+ $osVer = (Get-CimInstance Win32_OperatingSystem).Version
22
+ $arch = $env:PROCESSOR_ARCHITECTURE
23
+
24
+ # ---------- hardware ----------
25
+ $cpuObj = Get-CimInstance Win32_Processor | Select-Object -First 1
26
+ $cpuModel = if ($cpuObj) { "$($cpuObj.Name.Trim()) ($($cpuObj.NumberOfCores)C/$($cpuObj.NumberOfLogicalProcessors)T)" } else { $null }
27
+ $cpuCores = if ($cpuObj) { [int]$cpuObj.NumberOfLogicalProcessors } else { 0 }
28
+ $cs = Get-CimInstance Win32_ComputerSystem
29
+ $memGB = [math]::Round($cs.TotalPhysicalMemory / 1GB)
30
+ $pf = Get-CimInstance Win32_PageFileUsage | Select-Object -First 1
31
+ $swapGB = if ($pf) { [math]::Round($pf.AllocatedBaseSize / 1024) } else { 0 }
32
+
33
+ $gpuObj = Get-CimInstance Win32_VideoController | Select-Object -First 1
34
+ $gpu = if ($gpuObj) {
35
+ $vramMb = if ($gpuObj.AdapterRAM) { [math]::Round($gpuObj.AdapterRAM / 1MB) } else { $null }
36
+ [ordered]@{ vendor = ($gpuObj.Name -split ' ')[0]; model = $gpuObj.Name; vram_mb = $vramMb; driver = $gpuObj.DriverVersion }
37
+ } else {
38
+ [ordered]@{ vendor = $null; model = $null; vram_mb = $null; driver = $null }
39
+ }
40
+
41
+ $disks = @(Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Used -gt 0 -or $_.Free -gt 0 } | ForEach-Object {
42
+ $total = [math]::Round(($_.Used + $_.Free) / 1GB)
43
+ $free = [math]::Round($_.Free / 1GB)
44
+ [ordered]@{ mount = "$($_.Name):"; total_gb = $total; free_gb = $free }
45
+ })
46
+
47
+ # ---------- languages ----------
48
+ $lang = [ordered]@{
49
+ nodejs = Get-Ver node '--version' 'v?([\d.]+)'
50
+ python = Get-Ver python '--version' '([\d.]+)'
51
+ rust = Get-Ver rustc '--version' 'rustc ([\w.]+)'
52
+ go = Get-Ver go 'version' 'go version go([\w.]+)'
53
+ java = Get-Ver java '-version' '"([\w.]+)"'
54
+ dotnet = Get-Ver dotnet '--version' '([\d.]+)'
55
+ r = Get-Ver R '--version' 'R version ([\w.]+)'
56
+ }
57
+
58
+ # ---------- package managers ----------
59
+ $pm = [ordered]@{}
60
+ foreach ($m in 'npm','pnpm','yarn','bun','uv','conda','cargo','pip','winget','scoop','choco') {
61
+ $v = Get-Ver $m '--version' '([\d][\w.]*)'
62
+ $pm[$m] = if ($v) { $v } elseif (Test-Cmd $m) { 'installed' } else { $null }
63
+ }
64
+
65
+ # ---------- env managers ----------
66
+ $condaEnvs = @()
67
+ if (Test-Cmd conda) {
68
+ $condaEnvs = @(conda env list 2>$null | Where-Object { $_ -and $_ -notmatch '^#' } | ForEach-Object { ($_ -split '\s+')[0] } | Where-Object { $_ })
69
+ }
70
+ $uvPythons = @()
71
+ if (Test-Cmd uv) {
72
+ $uvPythons = @(uv python list 2>$null | Where-Object { $_ } | ForEach-Object { ($_ -split '\s+')[0] } | Where-Object { $_ -and $_ -notmatch '^-' } | Select-Object -First 10)
73
+ }
74
+
75
+ # ---------- proxy ----------
76
+ $proxyPorts = @()
77
+ foreach ($p in 1080, 7890, 7897, 8118, 10808, 8888) {
78
+ $client = New-Object System.Net.Sockets.TcpClient
79
+ try {
80
+ $task = $client.ConnectAsync('127.0.0.1', $p)
81
+ if ($task.Wait(500) -and $client.Connected) { $proxyPorts += "$p" }
82
+ } catch { } finally { $client.Dispose() }
83
+ }
84
+
85
+ # ---------- network topology (init 时探测) ----------
86
+ $net = [ordered]@{
87
+ vps_alias = $null; vps_ip = $null; frp_svc = $null
88
+ nginx_server_name = $null; nginx_port = $null
89
+ listen_ports = @()
90
+ }
91
+ # SSH config (OpenSSH): 解析 Host / HostName
92
+ $sshCfg = Join-Path $env:USERPROFILE '.ssh\config'
93
+ if (Test-Path $sshCfg) {
94
+ $lines = Get-Content $sshCfg -ErrorAction SilentlyContinue
95
+ $inBlock = $false
96
+ foreach ($line in $lines) {
97
+ if ($line -match '^\s*Host\s+') {
98
+ if (-not $inBlock -and -not $net.vps_alias) {
99
+ $net.vps_alias = ($line -replace '^\s*Host\s+', '').Trim() -split '\s+' | Select-Object -First 1
100
+ $inBlock = $true
101
+ } elseif ($inBlock) { break }
102
+ } elseif ($inBlock -and $line -match '^\s*HostName\s+(.+)$') {
103
+ $net.vps_ip = $Matches[1].Trim(); break
104
+ }
105
+ }
106
+ }
107
+ # frp service / nginx: Windows 无 systemctl & 通常无 nginx,留 null
108
+ # 端口扫描 (回环 listen)
109
+ $scanPorts = 22, 80, 443, 1080, 7890, 8787, 8765, 8767, 8090, 8000, 8080, 8443, 22022, 2222
110
+ foreach ($p in $scanPorts) {
111
+ $client = New-Object System.Net.Sockets.TcpClient
112
+ try {
113
+ $task = $client.ConnectAsync('127.0.0.1', $p)
114
+ if ($task.Wait(300) -and $client.Connected) { $net.listen_ports += "$p" }
115
+ } catch { } finally { $client.Dispose() }
116
+ }
117
+
118
+ # ---------- codebase-memory-mcp ----------
119
+ $cbCli = Test-Cmd 'codebase-memory-mcp'
120
+ $cbCfg = $false
121
+ foreach ($f in "$env:USERPROFILE\.claude.json", "$env:USERPROFILE\.claude\settings.json", "$env:USERPROFILE\.codex\config.toml", "$env:USERPROFILE\.gemini\settings.json") {
122
+ if (Test-Path $f) {
123
+ if (Select-String -Path $f -Pattern 'codebase-memory' -Quiet -ErrorAction SilentlyContinue) { $cbCfg = $true; break }
124
+ }
125
+ }
126
+ if ($cbCli) { $cbCfg = $true }
127
+
128
+ # ---------- output ----------
129
+ $out = [ordered]@{
130
+ os = [ordered]@{ name = $osName; version = $osVer; arch = $arch }
131
+ shell = 'powershell'
132
+ hardware = [ordered]@{
133
+ cpu_model = $cpuModel
134
+ cpu_cores = $cpuCores
135
+ memory_gb = $memGB
136
+ swap_gb = $swapGB
137
+ avx2 = $null
138
+ gpu = $gpu
139
+ disks = $disks
140
+ }
141
+ languages = $lang
142
+ package_managers = $pm
143
+ env_managers = [ordered]@{ conda_envs = $condaEnvs; uv_pythons = $uvPythons }
144
+ proxy = [ordered]@{
145
+ env_http = $env:HTTP_PROXY
146
+ env_https = $env:HTTPS_PROXY
147
+ open_local_ports = $proxyPorts
148
+ }
149
+ network = $net
150
+ codebase_mcp = [ordered]@{ cli_available = $cbCli; mcp_configured = $cbCfg }
151
+ tools = [ordered]@{
152
+ git = (Get-Ver git '--version' 'git version ([\w.]+)')
153
+ gh = (Test-Cmd gh)
154
+ rg = (Test-Cmd rg)
155
+ docker = (Test-Cmd docker)
156
+ }
157
+ }
158
+
159
+ $out | ConvertTo-Json -Depth 6
@@ -0,0 +1,201 @@
1
+ #!/usr/bin/env bash
2
+ # dev-host-init: cross-platform host environment detection (Linux / macOS / WSL / Git Bash)
3
+ # Outputs a single JSON object to stdout. Every probe silently degrades to null/false/[].
4
+ # Companion of host-scan.ps1 (Windows native). Consumed by dev-host-init Phase 2/5 rendering.
5
+
6
+ set -euo pipefail
7
+
8
+ OS_NAME="$(uname -s 2>/dev/null || echo Unknown)"
9
+ IS_MAC=0; [[ "$OS_NAME" == "Darwin" ]] && IS_MAC=1
10
+
11
+ json_str() { printf '"%s"' "${1:-}"; }
12
+ json_opt_str() { if [[ -n "${1:-}" ]]; then printf '"%s"' "$1"; else echo 'null'; fi; }
13
+
14
+ # ---------- OS & shell ----------
15
+ echo '{'
16
+ echo " \"os\": {"
17
+ echo -n ' "name": '; json_str "$OS_NAME"; echo ","
18
+ echo -n ' "version": '; json_str "$(uname -r 2>/dev/null || echo Unknown)"; echo ","
19
+ echo -n ' "arch": '; json_str "$(uname -m 2>/dev/null || echo Unknown)"
20
+ echo ' },'
21
+ echo -n ' "shell": '; json_opt_str "${SHELL:-}"; echo ','
22
+
23
+ # ---------- hardware ----------
24
+ echo ' "hardware": {'
25
+ if [[ $IS_MAC -eq 1 ]]; then
26
+ CPU_MODEL="$(sysctl -n machdep.cpu.brand_string 2>/dev/null || true)"
27
+ [[ -z "$CPU_MODEL" ]] && CPU_MODEL="$(sysctl -n hw.model 2>/dev/null || true)"
28
+ CPU_CORES="$(sysctl -n hw.ncpu 2>/dev/null || echo 0)"
29
+ MEM_GB=$(( $(sysctl -n hw.memsize 2>/dev/null || echo 0) / 1073741824 ))
30
+ SWAP_GB=0
31
+ else
32
+ CPU_MODEL="$(lscpu 2>/dev/null | awk -F': +' '/^Model name|^型号名称/{print $2; exit}' || true)"
33
+ [[ -z "$CPU_MODEL" ]] && CPU_MODEL="$(awk -F': ' '/^model name/{print $2; exit}' /proc/cpuinfo 2>/dev/null || true)"
34
+ CPU_CORES="$(nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || echo 0)"
35
+ MEM_GB=$(( $(awk '/^MemTotal/{print $2}' /proc/meminfo 2>/dev/null || echo 0) / 1048576 ))
36
+ SWAP_GB=$(( $(awk '/^SwapTotal/{print $2}' /proc/meminfo 2>/dev/null || echo 0) / 1048576 ))
37
+ fi
38
+ echo -n ' "cpu_model": '; json_opt_str "$CPU_MODEL"; echo ','
39
+ echo " \"cpu_cores\": ${CPU_CORES:-0},"
40
+ echo " \"memory_gb\": ${MEM_GB:-0},"
41
+ echo " \"swap_gb\": ${SWAP_GB:-0},"
42
+
43
+ # AVX2 note (x86 Linux only; macOS/ARM => null)
44
+ AVX2="$(grep -m1 -o 'avx2' /proc/cpuinfo 2>/dev/null || true)"
45
+ if [[ -n "$AVX2" ]]; then AVX2_JSON=true; else AVX2_JSON=false; fi
46
+ echo " \"avx2\": ${AVX2_JSON},"
47
+
48
+ # GPU
49
+ echo ' "gpu": {'
50
+ if command -v nvidia-smi &>/dev/null; then
51
+ echo ' "vendor": "nvidia",'
52
+ echo -n ' "model": '; json_opt_str "$(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null | head -1)"; echo ','
53
+ echo " \"vram_mb\": $(nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits 2>/dev/null | head -1 || echo 0),"
54
+ echo -n ' "driver": '; json_opt_str "$(nvidia-smi --query-gpu=driver_version --format=csv,noheader 2>/dev/null | head -1)"
55
+ elif command -v rocm-smi &>/dev/null; then
56
+ echo ' "vendor": "amd",'
57
+ echo ' "model": "detected", "vram_mb": null, "driver": null'
58
+ elif [[ $IS_MAC -eq 1 && "$CPU_MODEL" == Apple* ]]; then
59
+ echo ' "vendor": "apple",'
60
+ echo -n ' "model": '; json_opt_str "$CPU_MODEL"; echo ','
61
+ echo ' "vram_mb": null, "driver": null'
62
+ else
63
+ echo ' "vendor": null, "model": null, "vram_mb": null, "driver": null'
64
+ fi
65
+ echo ' },'
66
+
67
+ # disks: mount,total_gb,free_gb — real filesystems only, max 5
68
+ echo ' "disks": ['
69
+ DF_OUT="$(df -l -k 2>/dev/null | awk 'NR>1 && $1 !~ /^(tmpfs|devfs|devtmpfs|map|overlay|squashfs|proc|sysfs|cgroup|udev)/ && $6 !~ /^\/(dev|proc|sys|run)(\/|$)/ {print $6" "$2" "$4}' | head -5 || true)"
70
+ FIRST=1
71
+ while read -r mnt total avail; do
72
+ [[ -z "${mnt:-}" ]] && continue
73
+ [[ $FIRST -eq 1 ]] || echo ','
74
+ FIRST=0
75
+ echo " {\"mount\": $(json_str "$mnt"), \"total_gb\": $((total/1048576)), \"free_gb\": $((avail/1048576))}"
76
+ done <<< "$DF_OUT"
77
+ echo ''
78
+ echo ' ]'
79
+ echo ' },'
80
+
81
+ # ---------- languages ----------
82
+ echo ' "languages": {'
83
+ echo -n ' "nodejs": '; command -v node &>/dev/null && json_str "$(node --version 2>/dev/null | tr -d v)" || echo 'null'; echo ','
84
+ if command -v python3 &>/dev/null; then echo -n ' "python": '; json_str "$(python3 --version 2>/dev/null | awk '{print $2}')"
85
+ elif command -v python &>/dev/null; then echo -n ' "python": '; json_str "$(python --version 2>/dev/null | awk '{print $2}')"
86
+ else echo -n ' "python": null'; fi; echo ','
87
+ echo -n ' "rust": '; command -v rustc &>/dev/null && json_str "$(rustc --version 2>/dev/null | awk '{print $2}')" || echo 'null'; echo ','
88
+ echo -n ' "go": '; command -v go &>/dev/null && json_str "$(go version 2>/dev/null | awk '{print $3}' | tr -d go)" || echo 'null'; echo ','
89
+ echo -n ' "java": '; command -v java &>/dev/null && json_str "$(java -version 2>&1 | head -1 | awk -F'"' '{print $2}')" || echo 'null'; echo ','
90
+ echo -n ' "dotnet": '; command -v dotnet &>/dev/null && json_str "$(dotnet --version 2>/dev/null)" || echo 'null'; echo ','
91
+ echo -n ' "r": '; command -v R &>/dev/null && json_str "$(R --version 2>/dev/null | head -1 | awk '{print $3}')" || echo 'null'
92
+ echo ' },'
93
+
94
+ # ---------- package managers ----------
95
+ echo ' "package_managers": {'
96
+ for pm in npm pnpm yarn bun uv conda cargo pip; do
97
+ case $pm in
98
+ pip) VER="$(pip --version 2>/dev/null | awk '{print $2}' || true)" ;;
99
+ *) VER="$($pm --version 2>/dev/null | awk '{print $NF}' | head -1 || true)" ;;
100
+ esac
101
+ # keep only plausible version tokens (digits or x.y.z-ish)
102
+ if [[ -n "$VER" && "$VER" =~ [0-9] ]]; then echo " \"$pm\": $(json_str "$VER"),"
103
+ else echo " \"$pm\": null,"; fi
104
+ done
105
+ # brew (macOS/linuxbrew)
106
+ echo -n ' "brew": '; command -v brew &>/dev/null && json_str "$(brew --version 2>/dev/null | head -1 | awk '{print $2}')" || echo 'null'
107
+ echo ' },'
108
+
109
+ # ---------- env managers ----------
110
+ echo ' "env_managers": {'
111
+ echo -n ' "conda_envs": ['
112
+ if command -v conda &>/dev/null; then
113
+ FIRST=1
114
+ while read -r e; do
115
+ [[ -z "$e" ]] && continue
116
+ [[ $FIRST -eq 1 ]] || printf ', '
117
+ FIRST=0; printf '"%s"' "$e"
118
+ done < <(conda env list 2>/dev/null | grep -v '^#' | awk 'NF{print $1}' || true)
119
+ fi
120
+ echo '],'
121
+ echo -n ' "uv_pythons": ['
122
+ if command -v uv &>/dev/null; then
123
+ FIRST=1
124
+ while read -r e; do
125
+ [[ -z "$e" ]] && continue
126
+ [[ $FIRST -eq 1 ]] || printf ', '
127
+ FIRST=0; printf '"%s"' "$e"
128
+ done < <(uv python list 2>/dev/null | awk 'NF && $1!~"^-"{print $1}' | head -10 || true)
129
+ fi
130
+ echo ']'
131
+ echo ' },'
132
+
133
+ # ---------- proxy ----------
134
+ echo ' "proxy": {'
135
+ echo -n ' "env_http": '; json_opt_str "${http_proxy:-${HTTP_PROXY:-}}"; echo ','
136
+ echo -n ' "env_https": '; json_opt_str "${https_proxy:-${HTTPS_PROXY:-}}"; echo ','
137
+ echo -n ' "open_local_ports": ['
138
+ FIRST=1
139
+ for port in 1080 7890 7897 8118 10808 8888; do
140
+ if timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$port" 2>/dev/null; then
141
+ [[ $FIRST -eq 1 ]] || printf ', '
142
+ FIRST=0; printf '"%s"' "$port"
143
+ fi
144
+ done
145
+ echo ']'
146
+ echo ' },'
147
+ # ---------- network topology (init 时探测) ----------
148
+ echo ' "network": {'
149
+ # SSH alias -> VPS IP (解析 ~/.ssh/config)
150
+ vps_ip=""; vps_alias=""
151
+ if [ -f "$HOME/.ssh/config" ]; then
152
+ vps_alias=$(awk '/^Host /{a=$2} a!="" && /HostName /{print a; exit}' "$HOME/.ssh/config" 2>/dev/null)
153
+ vps_ip=$(awk '/^Host /{a=$2} a!="" && /HostName /{print $2; exit}' "$HOME/.ssh/config" 2>/dev/null)
154
+ fi
155
+ echo -n ' "vps_alias": '; json_opt_str "${vps_alias}"; echo ','
156
+ echo -n ' "vps_ip": '; json_opt_str "${vps_ip}"; echo ','
157
+ # FRP systemd service
158
+ frp_svc=$(systemctl list-units --type=service --all 2>/dev/null | awk '/frpc|frp/{print $1; exit}' | head -1 || true)
159
+ echo -n ' "frp_svc": '; json_opt_str "${frp_svc}"; echo ','
160
+ # nginx server_name / port (本机已装时)
161
+ ngx_name=""; ngx_port=""
162
+ if [ -d /etc/nginx ]; then
163
+ ngx_name=$(grep -rhoE 'server_name[[:space:]]+[^;]+' /etc/nginx/sites-available /etc/nginx/conf.d 2>/dev/null \
164
+ | awk '$2 != "_" && $2 != "example.com" && $2 != "default_server" {print $2; exit}')
165
+ ngx_port=$(grep -rhoE 'listen[[:space:]]+[0-9]+' /etc/nginx/sites-available /etc/nginx/conf.d 2>/dev/null | awk '{print $2; exit}')
166
+ fi
167
+ echo -n ' "nginx_server_name": '; json_opt_str "${ngx_name}"; echo ','
168
+ echo -n ' "nginx_port": '; json_opt_str "${ngx_port}"; echo ','
169
+ # 端口扫描 (回环 listen, 含本机服务端口)
170
+ scan_ports="22 80 443 1080 7890 8787 8765 8767 8090 8000 8080 8443 22022 2222"
171
+ echo -n ' "listen_ports": ['
172
+ FIRST=1
173
+ for port in $scan_ports; do
174
+ if timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$port" 2>/dev/null; then
175
+ if [ $FIRST -eq 1 ]; then FIRST=0; else printf ','; fi
176
+ printf '"%s"' "$port"
177
+ fi
178
+ done
179
+ echo ' ]'
180
+ echo ' },'
181
+
182
+ # ---------- codebase-memory-mcp ----------
183
+ echo ' "codebase_mcp": {'
184
+ if command -v codebase-memory-mcp &>/dev/null; then CB_CLI=true; else CB_CLI=false; fi
185
+ echo " \"cli_available\": ${CB_CLI},"
186
+ CB_CFG=0
187
+ for f in "$HOME/.claude.json" "$HOME/.claude/settings.json" "$HOME/.codex/config.toml" "$HOME/.gemini/settings.json"; do
188
+ if [[ -f "$f" ]] && grep -q 'codebase-memory' "$f" 2>/dev/null; then CB_CFG=1; break; fi
189
+ done
190
+ [[ $CB_CLI == true ]] && CB_CFG=1
191
+ if [[ $CB_CFG -eq 1 ]]; then echo ' "mcp_configured": true'; else echo ' "mcp_configured": false'; fi
192
+ echo ' },'
193
+
194
+ # ---------- tools ----------
195
+ echo ' "tools": {'
196
+ echo -n ' "git": '; command -v git &>/dev/null && json_str "$(git --version 2>/dev/null | awk '{print $3}')" || echo 'null'; echo ','
197
+ echo -n ' "gh": '; command -v gh &>/dev/null && echo true || echo false; echo ','
198
+ echo -n ' "rg": '; command -v rg &>/dev/null && echo true || echo false; echo ','
199
+ echo -n ' "docker": '; command -v docker &>/dev/null && echo true || echo false
200
+ echo ' }'
201
+ echo '}'