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,229 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ tools-catalog.py — dev-host-init 部署方式目录(问卷选项 + 命令含真实下载源)
4
+ ============================================================================
5
+ 被 render-now.py 引用:提供「工具 → 多个安装方式(源码/二进制/包管理器/官方安装器)」,
6
+ 供 init 问卷选择与「开发工具部署计划」渲染。同时含「美术风格预设」与「自由文本配色生成」。
7
+
8
+ 【脱敏】本文件只含公开下载源与通用占位(<版本>、<仓库URL>);不出现仓库本地绝对路径、
9
+ SSH 别名、VPS IP 或任何本机专属字面量。Windows 用 %LOCALAPPDATA% 兜底、POSIX 只有 $HOME。
10
+ """
11
+ import os
12
+ import hashlib
13
+ import json
14
+
15
+
16
+ # ---------- 工具部署目录:name → {windows/posix: [选项]}, note ----------
17
+ # 每个选项 {label, kind(源码/二进制/包管理器/官方安装器), cmd}
18
+ TOOL_INSTALL = {
19
+ "codebase-memory-mcp": {
20
+ "note": ("纯 C 实现:npm/uv/pip 渠道背后仍是下载预编译二进制,无真编译产物。"
21
+ "Linux 低 glibc 需用 -portable 包或源码编译(DEPLOYMENT.zh-CN.md 有实测)。"
22
+ "装后 `codebase-memory-mcp install -y` 自动配置 Claude/Codex 的 MCP + hook + skill。"),
23
+ "windows": [
24
+ {"label": "官方安装脚本(推荐)", "kind": "二进制", "cmd":
25
+ 'irm https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.ps1 | iex'},
26
+ {"label": "源码本地编译", "kind": "源码", "cmd":
27
+ 'git clone https://github.com/DeusData/codebase-memory-mcp && cd codebase-memory-mcp '
28
+ '&& scripts/build.sh && copy build\\c\\codebase-memory-mcp.exe %LOCALAPPDATA%\\bin\\'},
29
+ {"label": "npm 全局", "kind": "包管理器", "cmd": "npm i -g codebase-memory-mcp"},
30
+ {"label": "uv tool", "kind": "包管理器", "cmd": "uv tool install codebase-memory-mcp"},
31
+ ],
32
+ "posix": [
33
+ {"label": "官方安装脚本(推荐)", "kind": "二进制", "cmd":
34
+ 'curl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.sh | bash'},
35
+ {"label": "源码本地编译", "kind": "源码", "cmd":
36
+ "git clone https://github.com/DeusData/codebase-memory-mcp && cd codebase-memory-mcp "
37
+ "&& scripts/build.sh && cp build/c/codebase-memory-mcp ~/.local/bin/"},
38
+ {"label": "npm 全局", "kind": "包管理器", "cmd": "npm i -g codebase-memory-mcp"},
39
+ {"label": "uv tool", "kind": "包管理器", "cmd": "uv tool install codebase-memory-mcp"},
40
+ ],
41
+ },
42
+ "pi(@earendil-works/pi-coding-agent)": {
43
+ "note": "官方发布渠道以 README/官网为准;Windows 本机走 npm 已装 0.84.4。",
44
+ "windows": [
45
+ {"label": "npm 全局(推荐)", "kind": "包管理器", "cmd": "npm i -g @earendil-works/pi-coding-agent"},
46
+ {"label": "官网二进制/安装器", "kind": "二进制", "cmd": "<官方文档URL> 提供 prebuilt 安装器"},
47
+ {"label": "从源码", "kind": "源码", "cmd":
48
+ "git clone <pi仓库URL> && cd <目录> && npm ci && npm run build && npm i -g ."},
49
+ ],
50
+ "posix": [
51
+ {"label": "npm 全局(推荐)", "kind": "包管理器", "cmd": "npm i -g @earendil-works/pi-coding-agent"},
52
+ {"label": "官网二进制/安装器", "kind": "二进制", "cmd": "<官方文档URL> 提供 prebuilt 安装器"},
53
+ ],
54
+ },
55
+ "gh / GitHub CLI": {
56
+ "note": "免密快速部署:`gh auth login`(凭据存本机,勾选 HTTPS/SSH 凭据)后一条命令做远端操作。",
57
+ "windows": [
58
+ {"label": "winget(包管理器)", "kind": "包管理器", "cmd": "winget install GitHub.cli"},
59
+ {"label": "官网二进制(MSI)", "kind": "二进制", "cmd": "从 https://cli.github.com 下载 .msi"},
60
+ {"label": "源码(go build)", "kind": "源码", "cmd": "git clone https://github.com/cli/cli && cd cli && make"},
61
+ ],
62
+ "posix": [
63
+ {"label": "apt(包管理器)", "kind": "包管理器", "cmd": "sudo apt install gh # 或 brew install gh"},
64
+ {"label": "官网二进制", "kind": "二进制", "cmd": "curl -fsSL https://cli.github.com/install.sh | sh"},
65
+ {"label": "源码(go build)", "kind": "源码", "cmd": "git clone https://github.com/cli/cli && cd cli && make"},
66
+ ],
67
+ },
68
+ "rg / ripgrep(强烈建议)": {
69
+ "note": "仓库全文检索依赖;缺失则 SKILL 建议 `rg --files`→回退 grep。",
70
+ "windows": [
71
+ {"label": "winget(包管理器)", "kind": "包管理器", "cmd": "winget install BurntSushi.ripgrep.MSVC"},
72
+ {"label": "官网二进制(zip)", "kind": "二进制", "cmd": "从 https://github.com/BurntSushi/ripgrep/releases 下载 zip 解压到 PATH"},
73
+ ],
74
+ "posix": [
75
+ {"label": "apt(包管理器)", "kind": "包管理器", "cmd": "sudo apt install ripgrep # 或 brew install ripgrep"},
76
+ {"label": "官网二进制", "kind": "二进制", "cmd": "从 releases 下载 static musl 包 放入 ~/.local/bin"},
77
+ ],
78
+ },
79
+ "uv(Python 管理)": {
80
+ "note": "本机已装 0.10.2;新项目 Python 用 uv venv。",
81
+ "windows": [
82
+ {"label": "winget(包管理器)", "kind": "包管理器", "cmd": "winget install astral-sh.uv"},
83
+ {"label": "官方安装器(PowerShell)", "kind": "官方安装器", "cmd": "powershell -c \"irm https://astral.sh/uv/install.ps1 | iex\""},
84
+ ],
85
+ "posix": [
86
+ {"label": "官方安装器", "kind": "官方安装器", "cmd": "curl -LsSf https://astral.sh/uv/install.sh | sh"},
87
+ ],
88
+ },
89
+ "node(Node.js)": {
90
+ "note": "多版本管理(源码 via nvm/fnm)、二进制(LTS 安装器)、包管理器(npm i -g)三条路由。",
91
+ "windows": [
92
+ {"label": "官方 LTS 安装器(二进制)", "kind": "二进制", "cmd": "winget install OpenJS.NodeJS.LTS # 或 nodejs.org LTS .msi"},
93
+ {"label": "nvm-windows(源码多版本)", "kind": "源码", "cmd": "winget install CoreyButler.NVMforWindows"},
94
+ ],
95
+ "posix": [
96
+ {"label": "nvm(源码多版本)", "kind": "源码", "cmd":
97
+ "curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v<版本>/install.sh | bash && nvm install --lts"},
98
+ {"label": "官方 tarball(二进制)", "kind": "二进制", "cmd": "从 nodejs.org 下载 LTS tar.xz 解压到 ~/.local"},
99
+ ],
100
+ },
101
+ }
102
+
103
+
104
+ # ---------- 美术风格预设(描述性,不唯一于任何领域) ----------
105
+ ART_STYLES = [
106
+ {"id": "engineering-calm", "name": "工程冷静 · 深海蓝灰",
107
+ "desc": "低饱和蓝灰主色 + 冷感强调青/钛,克制、专业、可读性优先;适合前后端/基建/CLI 工具/监控面板。",
108
+ "palette": {"primary": "#4A6572", "accent": "#1BA1C6", "bg": "#F4F7F8", "text": "#24303A"},
109
+ "gradient": ["#4A6572", "#1BA1C6"]},
110
+ {"id": "academic-muted", "name": "科研学术 · 暖纸古蓝",
111
+ "desc": "米白纸底 + 古蓝/暗红点缀,克制的数据可视化色;适合论文/报表/生信/文献综述/学术海报。",
112
+ "palette": {"primary": "#A4443C", "accent": "#3A5A78", "bg": "#FAF7F0", "text": "#333A40"},
113
+ "gradient": ["#F0EDE4", "#A4443C"]},
114
+ {"id": "warm-human", "name": "温暖人文 · 焦糖暖橙",
115
+ "desc": "柔和奶油底 + 焦糖/珊瑚暖色,人文感强;适合内容站/社区/教育/医疗/非营利向界面与 PPT。",
116
+ "palette": {"primary": "#C2703D", "accent": "#D98E73", "bg": "#FFF6EE", "text": "#3D3028"},
117
+ "gradient": ["#FFF6EE", "#C2703D"]},
118
+ {"id": "dark-premium", "name": "暗黑高级 · 墨黑鎏金",
119
+ "desc": "近黑底 + 极光强调(金/青),NV 级高级感;适合开发者工具/仪表盘/深色主题产品。",
120
+ "palette": {"primary": "#E3B341", "accent": "#35E0E0", "bg": "#14161B", "text": "#E9EDF2"},
121
+ "gradient": ["#14161B", "#E3B341"]},
122
+ {"id": "nature-fresh", "name": "自然生态 · 苔绿雾松",
123
+ "desc": "低饱和苔绿 + 陶土/雾蓝语义,透气的自然感;适合生物/医药/环保/健康类应用与图表。",
124
+ "palette": {"primary": "#5E8875", "accent": "#C79A6B", "bg": "#F5F7F2", "text": "#2E4038"},
125
+ "gradient": ["#F5F7F2", "#5E8875"]},
126
+ {"id": "art-vivid", "name": "艺术活力 · 钴蓝朱红",
127
+ "desc": "高饱和钴蓝 + 朱红/橙黄点缀,年轻有张力;适合创意/平面设计/插画/营销/品牌物料与演示。",
128
+ "palette": {"primary": "#2E5CB8", "accent": "#E2583E", "bg": "#FAFAF5", "text": "#1D2233"},
129
+ "gradient": ["#FAFAF5", "#2E5CB8"]},
130
+ ]
131
+
132
+
133
+ def style_by_id(sid):
134
+ return next((s for s in ART_STYLES if s["id"] == sid), None)
135
+
136
+
137
+ def palette_text(style, task_hint=""):
138
+ c = style["palette"]
139
+ lines = [
140
+ "## 配色基调(init 问卷生成;可随时在 agent-reference/visualization.md 自调)", "",
141
+ f"- 风格:{style['name']} — {style['desc']}",
142
+ f"- 主基调:{c['primary']} / 强调:{c['accent']} / 背景:{c['bg']} / 正文:{c['text']}",
143
+ f"- 语义渐变:{style['gradient'][0]} → {style['gradient'][1]}",
144
+ ]
145
+ if task_hint:
146
+ lines.insert(1, f"> 任务提示:{task_hint}\n")
147
+ return "\n".join(lines)
148
+
149
+
150
+ def auto_palette(seed_text):
151
+ """自由文本 → 初始配色提案(确定性、零网络、零随机)。
152
+
153
+ 规则:从种子取稳定哈希映射到离散「色相族」,叠加 CBDR 明暗对比与可读性建议。
154
+ 不是"智能设计器",只是无手调基础下保证不刺眼、有记忆点的人类可改起点。
155
+ """
156
+ if not seed_text:
157
+ return ""
158
+ b = hashlib.sha256(seed_text.encode("utf-8")).digest()
159
+ fams = [
160
+ ("深海蓝", "#1A4B6E", "#2E86AB", "#A8D8EA"),
161
+ ("暮紫", "#3D348B", "#6A5AE0", "#D0C4F0"),
162
+ ("暖橙焦糖", "#B2501F", "#E8853D", "#F6D9B8"),
163
+ ("苔绿", "#4F7A5B", "#7BA58B", "#CCE0D2"),
164
+ ("朱红", "#A62A2A", "#E2574B", "#F6CDCB"),
165
+ ("金棕", "#A87C2C", "#D4A940", "#F0E2C0"),
166
+ ("青瓷", "#2F6D6D", "#4E9E9E", "#C3E5E5"),
167
+ ("雾灰高级", "#46494D", "#7E8A93", "#D9E0E4"),
168
+ ]
169
+ name, dark, mid, light = fams[b[0] % len(fams)]
170
+ accent = "#E2B341" if b[1] % 2 else "#E2574B"
171
+ bg = "#FAF8F4" if b[2] % 2 else "#F4F6F8"
172
+ text = "#232A30"
173
+ return (
174
+ "## 配色基调(由你的自由文本生成的初始提案;喜欢就留,不喜欢在 visualization.md 改)\n\n"
175
+ f"- 种子:`{seed_text[:40]}{'…' if len(seed_text) > 40 else ''}`\n"
176
+ f"- 主基调:{dark} / 强调:{accent} / 背景:{bg} / 正文:{text}\n"
177
+ f"- 语义渐变:{light} → {mid} → {dark}(分类可用 {name} 系做主线,语义冷暖可再加一极)\n"
178
+ "- 建议:正文对比度优先(深底浅字或浅底深字);类别色 ≥6 时拉开色相,避免接近色混淆。\n")
179
+
180
+
181
+ # ---------- 渲染:目录 JSON / 部署 TODO / 触发表 ----------
182
+ def catalog_for_platform():
183
+ kind = "windows" if os.name == "nt" else "posix"
184
+ out = {}
185
+ for name, spec in TOOL_INSTALL.items():
186
+ opts = spec.get(kind, [])
187
+ out[name] = {"options": [o["label"] for o in opts],
188
+ "kinds": [o["kind"] for o in opts],
189
+ "commands": {o["label"]: o["cmd"] for o in opts},
190
+ "note": spec.get("note", "")}
191
+ return out
192
+
193
+
194
+ def render_install_todo(picks):
195
+ """picks: {工具名: 选项label} → '## 开发工具部署计划' Markdown;空则返回 ''"""
196
+ if not picks:
197
+ return ""
198
+ kind = "windows" if os.name == "nt" else "posix"
199
+ lines = ["## 开发工具部署计划(本次 init 问卷选择)", ""]
200
+ for name, label in picks.items():
201
+ spec = TOOL_INSTALL.get(name, {})
202
+ opts = spec.get(kind, [])
203
+ cmd = next((o["cmd"] for o in opts if o["label"] == label), None)
204
+ lines.append(f"### {name} — {label}")
205
+ if cmd:
206
+ lines.append(f"```bash\n{cmd}\n```")
207
+ lines.append("")
208
+ lines.append("> 确认执行前请先逐条核对命令源的版本/Linux-dist 差异;不可逆源先 dry-run。")
209
+ return "\n".join(lines).strip()
210
+
211
+
212
+ def viz_trigger_table():
213
+ return ("| 科研配色、可视化、图表风格或你建的领域参考 | agent-reference/visualization.md |\n"
214
+ "| 需要一类风格/趋势速查或你的历史参考 | 自建 agent-reference/patterns.md |")
215
+
216
+
217
+ def catalog_json():
218
+ return json.dumps(catalog_for_platform(), ensure_ascii=False, indent=2)
219
+
220
+
221
+ if __name__ == "__main__":
222
+ import sys
223
+ if "--catalog" in sys.argv:
224
+ print(catalog_json())
225
+ elif "--auto-demo" in sys.argv:
226
+ print(auto_palette("前端 Vue 仪表盘,深色科技感"))
227
+ else:
228
+ print(render_install_todo({"codebase-memory-mcp": "官方安装脚本(推荐)",
229
+ "rg / ripgrep(强烈建议)": "winget(包管理器)"}))
@@ -0,0 +1,291 @@
1
+ /**
2
+ * graph-first-gate.ts — 三层代码阅读 fallback 硬闸门 + 逐轮铁律注入
3
+ *
4
+ * 主人钦定的硬逻辑(read 代码文件时按序判定,命中即 block):
5
+ *
6
+ * ┌─ Layer 1 图谱查询(默认起点)────────────────────────────┐
7
+ * │ 项目已索引 → 必须先用 codebase-memory 查询类工具: │
8
+ * │ search_graph / trace_path / get_code_snippet / query_graph │
9
+ * │ / get_architecture / search_code │
10
+ * └──── 未索引 / 索引过期?──→ Layer 2 ↓ ────────────────────┘
11
+ *
12
+ * ┌─ Layer 2 索引保障 ────────────────────────────────────────┐
13
+ * │ a. 项目未索引(无 .codebase-memory)→ 先 index_repository │
14
+ * │ b. 索引过期(目标文件 mtime > 索引 mtime,embedding 落后) │
15
+ * │ → 先 detect_changes / index_repository 更新 │
16
+ * │ 完成后回到 Layer 1 查图谱 —— 不允许索引完直接 read │
17
+ * └────────────────────────────────────────────────────────────┘
18
+ *
19
+ * ┌─ Layer 3 直读兜底(仅以下情形放行 read)───────────────────┐
20
+ * │ a. 本会话已有 ≥1 次图谱查询工具成功调用(tool_result 非 error)│
21
+ * │ b. 目标文件是本会话自己 edit/write 改过的(开发中读回) │
22
+ * │ c. 非代码文件(md/json/toml...)或路径不在 PROJECT_ROOTS 下 │
23
+ * │ d. 全局拦截次数达 MAX_BLOCKS(防死锁最后兜底) │
24
+ * └────────────────────────────────────────────────────────────┘
25
+ *
26
+ * 另:context 事件在每次 LLM 调用前把铁律合并进最后一条 user 消息
27
+ * (深拷贝不落盘、不累积、不破坏前缀 KV cache)。
28
+ *
29
+ * 安装:~/.pi/agent/extensions/ 全局自动加载;生效:重启 pi 或 /reload。
30
+ */
31
+
32
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
33
+ import { existsSync, readdirSync, statSync } from "node:fs";
34
+ import { dirname, join } from "node:path";
35
+ import { homedir } from "node:os";
36
+
37
+ // ============================== 配置 ==============================
38
+
39
+ /** 闸门管辖的项目根目录(其下的代码文件受三层 fallback 约束;系统库/vendor 等路径放行) */
40
+ const PROJECT_ROOTS = [join(homedir(), "Development")]; // 主开发根目录,按本机实际增删
41
+
42
+ /** 视为"代码文件"的后缀(读这些才走闸门;md/json/toml 等参考文件不拦) */
43
+ const CODE_EXT =
44
+ /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs|py|pyi|rs|go|java|c|h|cc|cpp|hpp|rb|php|sql|sh|scala|kt|swift|lua|vue|svelte|r|R|jl)$/;
45
+
46
+ /** Layer 1 查询类图谱工具(后缀匹配,兼容 server 前缀形式 codebase-memory-mcp_xxx) */
47
+ const QUERY_SUFFIXES = [
48
+ "search_graph",
49
+ "trace_path",
50
+ "get_code_snippet",
51
+ "query_graph",
52
+ "get_architecture",
53
+ "search_code",
54
+ ];
55
+
56
+ /** 同一会话 read 闸门最大拦截次数(超过后放行,MCP 不可用等死锁场景的最后兜底) */
57
+ const MAX_BLOCKS = 3;
58
+
59
+ /** 向上探测 .codebase-memory 的最大目录层数 */
60
+ const MAX_WALK = 12;
61
+
62
+ /** 索引 mtime 缓存有效期(ms)——期间内重复判定不重扫 .codebase-memory */
63
+ const IDX_MTIME_TTL = 30_000;
64
+
65
+ /** mtime 比较容差(ms),规避同秒写入抖动 */
66
+ const MTIME_EPSILON = 2_000;
67
+
68
+ // ============================== 状态 ==============================
69
+
70
+ let graphQueryOK = 0; // 本会话查询类图谱工具成功(tool_result 非 error)次数
71
+ let readBlockCount = 0; // 本会话 read 被拦截次数
72
+ const sessionEditedFiles = new Set<string>(); // 本会话 edit/write 改过的文件
73
+ const markerCache = new Map<string, string | null>(); // dir -> 所属已索引项目根(null=未索引)
74
+ const idxMtimeCache = new Map<string, { at: number; mtime: number }>();
75
+
76
+ function resetState() {
77
+ graphQueryOK = 0;
78
+ readBlockCount = 0;
79
+ sessionEditedFiles.clear();
80
+ }
81
+
82
+ // ============================== 判定辅助 ==============================
83
+
84
+ function isQueryTool(name: string): boolean {
85
+ return QUERY_SUFFIXES.some((s) => name === s || name.endsWith(`_${s}`));
86
+ }
87
+
88
+ function underProjectRoots(p: string): boolean {
89
+ return PROJECT_ROOTS.some((r) => p === r || p.startsWith(r + "/"));
90
+ }
91
+
92
+ /**
93
+ * 向上探测包含 .codebase-memory 的项目根。
94
+ * 返回 null 表示(PROJECT_ROOTS 范围内)未索引。结果按目录缓存。
95
+ */
96
+ function findIndexedRoot(filePath: string): string | null {
97
+ let dir = dirname(filePath);
98
+ const walked: string[] = [];
99
+ for (let i = 0; i < MAX_WALK; i++) {
100
+ if (markerCache.has(dir)) {
101
+ const hit = markerCache.get(dir)!;
102
+ for (const d of walked) markerCache.set(d, hit);
103
+ return hit;
104
+ }
105
+ if (!underProjectRoots(dir)) break; // 越过项目根边界即停
106
+ walked.push(dir);
107
+ if (existsSync(join(dir, ".codebase-memory"))) {
108
+ for (const d of walked) markerCache.set(d, dir);
109
+ return dir;
110
+ }
111
+ const parent = dirname(dir);
112
+ if (parent === dir) break;
113
+ dir = parent;
114
+ }
115
+ for (const d of walked) markerCache.set(d, null);
116
+ return null;
117
+ }
118
+
119
+ /** 已索引项目的索引新鲜度:.codebase-memory 内最新文件 mtime(带 TTL 缓存) */
120
+ function indexMtime(root: string): number {
121
+ const hit = idxMtimeCache.get(root);
122
+ if (hit && Date.now() - hit.at < IDX_MTIME_TTL) return hit.mtime;
123
+ let m = 0;
124
+ try {
125
+ for (const f of readdirSync(join(root, ".codebase-memory"))) {
126
+ try {
127
+ const s = statSync(join(root, ".codebase-memory", f));
128
+ if (s.mtimeMs > m) m = s.mtimeMs;
129
+ } catch {
130
+ /* 单文件 stat 失败忽略 */
131
+ }
132
+ }
133
+ } catch {
134
+ /* 目录读取失败按 0 处理 */
135
+ }
136
+ idxMtimeCache.set(root, { at: Date.now(), mtime: m });
137
+ return m;
138
+ }
139
+
140
+ function fileMtime(p: string): number {
141
+ try {
142
+ return statSync(p).mtimeMs;
143
+ } catch {
144
+ return 0;
145
+ }
146
+ }
147
+
148
+ /** 未索引时给出建议的项目根(PROJECT_ROOTS 下第一级子目录) */
149
+ function suggestRepoRoot(filePath: string): string {
150
+ for (const r of PROJECT_ROOTS) {
151
+ if (filePath.startsWith(r + "/")) {
152
+ const seg = filePath.slice(r.length + 1).split("/")[0];
153
+ return join(r, seg);
154
+ }
155
+ }
156
+ return dirname(filePath);
157
+ }
158
+
159
+ // ============================== 文案 ==============================
160
+
161
+ const PER_TURN_REMINDER = [
162
+ "[system-reminder · 三层代码阅读铁律 · 每轮生效]",
163
+ "read 代码文件前必须按序走 fallback,禁止跳层:",
164
+ " Layer 1 图谱查询:先用 codebase-memory MCP(search_graph / trace_path / get_code_snippet / query_graph / get_architecture / search_code)查代码结构与调用关系;",
165
+ " Layer 2 索引保障:项目未索引、或索引/embedding 过期(代码比索引新)时,先 index_repository 建索引 / detect_changes 检查更新,完成后回到 Layer 1 查图谱——不允许索引完直接 read;",
166
+ " Layer 3 直读兜底:仅当图谱确实无法满足(非代码文件、图谱查不到、本会话自己改动的文件)才直接 read。",
167
+ "本会话内图谱查询成功一次后闸门即放行;跳过 Layer 1/2 直接 read 项目代码 = 违规,会被工具闸门拦截。",
168
+ ].join("\n");
169
+
170
+ function reasonNoIndex(path: string): string {
171
+ return [
172
+ "⛔ 三层铁律 · Layer 2 拦截:该项目尚未建立 codebase-memory 索引。",
173
+ "正确动作:先调用 index_repository(repo_path 建议取 " + suggestRepoRoot(path) + ";模式按规模选 full/moderate/fast)建立索引与 embedding;",
174
+ "索引完成后回到 Layer 1 查图谱(search_graph / trace_path / get_code_snippet 等),最后才可直读。",
175
+ "若确属一次性临时片段不值得建索引,向主人说明理由后依赖拦截上限兜底。",
176
+ ].join("\n");
177
+ }
178
+
179
+ function reasonStaleIndex(path: string, root: string): string {
180
+ return [
181
+ "⛔ 三层铁律 · Layer 2 拦截:索引疑似过期——目标文件比索引新(embedding 落后于代码变更)。",
182
+ `目标:${path}(所属已索引项目:${root})`,
183
+ "正确动作:先 detect_changes 检查影响范围,或 index_repository 重新索引;完成后回到 Layer 1 查图谱,最后才可直读。",
184
+ "本会话内你自己刚改过的文件不受此拦截。",
185
+ ].join("\n");
186
+ }
187
+
188
+ const REASON_GRAPH_FIRST = [
189
+ "⛔ 三层铁律 · Layer 1 拦截:项目已建立 codebase-memory 索引,但本会话尚未有任何一次成功的图谱查询。",
190
+ "必须先用查询类工具:search_graph / trace_path / get_code_snippet / query_graph / get_architecture / search_code;",
191
+ "图谱确实无法回答后,再回来 read 具体行号(届时闸门已放行)。",
192
+ "这是 AGENTS.md 的强制规则(先问图谱,再无细节,最后才读文件),不是可选项。读 md/json/toml 等非代码文件不受此限制。",
193
+ ].join("\n");
194
+
195
+ // ============================== 扩展主体 ==============================
196
+
197
+ export default function graphFirstGate(pi: ExtensionAPI) {
198
+ // --- 会话生命周期:重置每会话状态 ---
199
+ pi.on("session_start", async (_event, ctx) => {
200
+ resetState();
201
+ if (ctx.hasUI && findIndexedRoot(join(ctx.cwd, "x"))) {
202
+ ctx.ui.notify("codebase-memory 索引已就绪:代码探索请先走图谱(三层铁律由闸门硬性执行)", "info");
203
+ }
204
+ });
205
+
206
+ // --- tool_call:记录本会话改动文件 + read 三层闸门判定 ---
207
+ pi.on("tool_call", async (event, ctx) => {
208
+ const name = event.toolName;
209
+
210
+ // 记录本会话 edit/write 改过的文件(Layer 3-b 放行依据)
211
+ if (name === "edit" || name === "write") {
212
+ const p = (event.input as { path?: string })?.path;
213
+ if (p) sessionEditedFiles.add(p);
214
+ return;
215
+ }
216
+
217
+ if (name !== "read") return;
218
+
219
+ const path: string = (event.input as { path?: string })?.path ?? "";
220
+
221
+ // Layer 3-c:非代码文件、项目区外 → 不管
222
+ if (!path || !CODE_EXT.test(path) || !underProjectRoots(path)) return;
223
+
224
+ // Layer 3-a:本会话已有成功的图谱查询 → 直读兜底合法
225
+ if (graphQueryOK > 0) return;
226
+
227
+ // Layer 3-d:拦截上限 → 防死锁最后兜底
228
+ if (readBlockCount >= MAX_BLOCKS) return;
229
+
230
+ // Layer 3-b:本会话自己改过的文件 → 开发中读回
231
+ if (sessionEditedFiles.has(path)) return;
232
+
233
+ readBlockCount++;
234
+ const root = findIndexedRoot(path);
235
+
236
+ // Layer 2-a:未索引 → 先建索引
237
+ if (root === null) {
238
+ if (ctx.hasUI) ctx.ui.notify(`铁律闸门 [Layer2·未索引] #${readBlockCount}/${MAX_BLOCKS}:${path}`, "warn");
239
+ return { block: true, reason: reasonNoIndex(path) };
240
+ }
241
+
242
+ // Layer 2-b:索引过期(目标文件比索引新)→ 先更新索引
243
+ if (fileMtime(path) > indexMtime(root) + MTIME_EPSILON) {
244
+ if (ctx.hasUI) ctx.ui.notify(`铁律闸门 [Layer2·索引过期] #${readBlockCount}/${MAX_BLOCKS}:${path}`, "warn");
245
+ return { block: true, reason: reasonStaleIndex(path, root) };
246
+ }
247
+
248
+ // Layer 1:已索引、未过期、没查过图谱 → 先查图谱
249
+ if (ctx.hasUI) ctx.ui.notify(`铁律闸门 [Layer1·图谱优先] #${readBlockCount}/${MAX_BLOCKS}:${path}`, "warn");
250
+ return { block: true, reason: REASON_GRAPH_FIRST };
251
+ });
252
+
253
+ // --- tool_result:仅"查询类图谱工具成功"才解锁 Layer 3(维护类/失败均不解锁)---
254
+ pi.on("tool_result", async (event) => {
255
+ if (event.isError) return;
256
+ if (isQueryTool(event.toolName)) graphQueryOK++;
257
+ });
258
+
259
+ // --- 逐轮注入:每次 LLM 调用前,把铁律合并进最后一条 user 消息 ---
260
+ pi.on("context", async (event) => {
261
+ const msgs = event.messages;
262
+ if (!msgs || msgs.length === 0) return;
263
+
264
+ const last = msgs[msgs.length - 1] as { role: string; content: unknown };
265
+
266
+ if (last.role === "user") {
267
+ msgs[msgs.length - 1] = {
268
+ ...last,
269
+ content: mergeContent(last.content, PER_TURN_REMINDER),
270
+ } as (typeof msgs)[number];
271
+ } else {
272
+ msgs.push({
273
+ role: "user",
274
+ content: PER_TURN_REMINDER,
275
+ } as (typeof msgs)[number]);
276
+ }
277
+
278
+ return { messages: msgs };
279
+ });
280
+ }
281
+
282
+ /** 把提醒文本合并进 user content(兼容 string 与 block 数组两种形态) */
283
+ function mergeContent(content: unknown, reminder: string): unknown {
284
+ if (typeof content === "string") {
285
+ return `${content}\n\n${reminder}`;
286
+ }
287
+ if (Array.isArray(content)) {
288
+ return [...content, { type: "text", text: reminder }];
289
+ }
290
+ return content;
291
+ }