@yiyi_zhang/laoshi 0.2.0-beta.3 → 0.3.0

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 (139) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +3 -2
  3. package/adapters/dsh/adapter.ts +22 -1
  4. package/adapters/dsh/dsh-runtime.ts +14 -3
  5. package/adapters/dsh/install.mjs +16 -4
  6. package/adapters/dsh/plugin/index.mjs +197 -18
  7. package/adapters/dsh/plugin/package.json +1 -1
  8. package/adapters/mogao/adapter.ts +10 -1
  9. package/adapters/mogao/mogao-runtime.ts +58 -23
  10. package/adapters/mogao/skill/setup.md +6 -0
  11. package/adapters/paseo/install.mjs +13 -4
  12. package/adapters/paseo/plugin/client/data.ts +13 -2
  13. package/adapters/paseo/plugin/client/detail.tsx +244 -4
  14. package/adapters/paseo/plugin/client/format.ts +25 -117
  15. package/adapters/paseo/plugin/client/overview.tsx +3 -3
  16. package/adapters/paseo/plugin/index.server.ts +2 -1
  17. package/adapters/paseo/plugin/package.json +1 -1
  18. package/adapters/paseo/plugin/paseo-plugin.json +1 -1
  19. package/adapters/paseo/plugin/server/handlers.ts +22 -4
  20. package/adapters/paseo/plugin/server/req.ts +17 -4
  21. package/adapters/paseo/plugin/shared/contracts.ts +28 -2
  22. package/adapters/paseo/plugin/shared/view-model.ts +425 -0
  23. package/bin/ensure-version.mjs +60 -0
  24. package/bin/req-doctor.mjs +5 -0
  25. package/bin/req.mjs +18 -0
  26. package/bin/start-pipeline.mjs +5 -0
  27. package/contracts/cli-json.md +3 -1
  28. package/docs/design/builtin-capabilities.md +2 -2
  29. package/docs/design/cli-adapter.md +1 -1
  30. package/docs/design/dsh-adapter.md +11 -11
  31. package/docs/design/shared-ui.md +43 -0
  32. package/docs/guide//345/234/250/346/221/270/351/253/230/344/270/212/344/275/277/347/224/250.md +2 -1
  33. package/docs/guide//345/256/211/350/243/205/344/270/216/345/215/207/347/272/247.md +13 -8
  34. package/docs/guide//347/234/237/345/256/236/347/216/257/345/242/203/350/265/260/346/237/245.md +78 -0
  35. package/docs/guide//347/273/264/346/212/244/350/200/205/346/214/207/345/215/227.md +36 -6
  36. package/engine/prompts/00-shared-context.md +7 -0
  37. package/engine/prompts/03-design.md +2 -0
  38. package/engine/prompts/04-design-review.md +5 -1
  39. package/engine/skill-fragments/defaults.md +5 -0
  40. package/engine/src/api.ts +11 -2
  41. package/engine/src/board.ts +435 -0
  42. package/engine/src/config.ts +23 -0
  43. package/engine/src/diagnose.ts +238 -0
  44. package/engine/src/doctor.ts +25 -0
  45. package/engine/src/estimate.ts +11 -0
  46. package/engine/src/extensions.ts +271 -0
  47. package/engine/src/handover-cmd.ts +47 -0
  48. package/engine/src/handover.ts +89 -0
  49. package/engine/src/history.ts +102 -0
  50. package/engine/src/joint.ts +49 -4
  51. package/engine/src/launch.ts +20 -5
  52. package/engine/src/main.ts +1 -1
  53. package/engine/src/messages.ts +58 -0
  54. package/engine/src/pipeline.ts +121 -5
  55. package/engine/src/platform.ts +6 -0
  56. package/engine/src/reply.ts +27 -6
  57. package/engine/src/semver.ts +21 -0
  58. package/engine/src/skills-render.ts +10 -1
  59. package/package.json +5 -2
  60. package/site-dist/404.html +2 -2
  61. package/site-dist/assets/{app.CXydUhZx.js → app.DZpVs0VH.js} +1 -1
  62. package/site-dist/assets/changelog.md.CdUYbro4.js +1 -0
  63. package/site-dist/assets/{changelog.md.BU-CvyJ1.lean.js → changelog.md.CdUYbro4.lean.js} +1 -1
  64. package/site-dist/assets/chunks/@localSearchIndexroot.CHr-ITwS.js +1 -0
  65. package/site-dist/assets/chunks/{VPLocalSearchBox.CIjDV0ax.js → VPLocalSearchBox.BHkmziy1.js} +1 -1
  66. package/site-dist/assets/chunks/{theme.CWtC1Kby.js → theme.BsPChbDE.js} +2 -2
  67. package/site-dist/assets/guide_dsh.md.D0XhcUHz.js +7 -0
  68. package/site-dist/assets/guide_dsh.md.D0XhcUHz.lean.js +7 -0
  69. package/site-dist/assets/{guide_getting-started.md.BxOxfic_.js → guide_getting-started.md.BDd3nU5n.js} +1 -1
  70. package/site-dist/assets/{guide_install.md.By4WxsJG.js → guide_install.md.SsIHMfUu.js} +7 -5
  71. package/site-dist/assets/{guide_install.md.By4WxsJG.lean.js → guide_install.md.SsIHMfUu.lean.js} +7 -5
  72. package/site-dist/assets/guide_maintainer.md.CvqvRle1.js +1 -0
  73. package/site-dist/assets/guide_maintainer.md.CvqvRle1.lean.js +1 -0
  74. package/site-dist/assets/{guide_mogao.md.S0eln1Pr.js → guide_mogao.md.TCu3lgE9.js} +2 -2
  75. package/site-dist/assets/{guide_mogao.md.S0eln1Pr.lean.js → guide_mogao.md.TCu3lgE9.lean.js} +2 -2
  76. package/site-dist/assets/guide_walkthrough.md.nj_PWP9Y.js +5 -0
  77. package/site-dist/assets/guide_walkthrough.md.nj_PWP9Y.lean.js +5 -0
  78. package/site-dist/assets/reference_contracts_cli-json.md.3iU9h4rw.js +1 -0
  79. package/site-dist/assets/reference_contracts_cli-json.md.3iU9h4rw.lean.js +1 -0
  80. package/site-dist/assets/{reference_design_builtin-capabilities.md.CZYtjo_v.js → reference_design_builtin-capabilities.md.k5NXkESv.js} +2 -2
  81. package/site-dist/assets/{reference_design_builtin-capabilities.md.CZYtjo_v.lean.js → reference_design_builtin-capabilities.md.k5NXkESv.lean.js} +2 -2
  82. package/site-dist/assets/{reference_design_cli-adapter.md.pJy3x6Un.js → reference_design_cli-adapter.md.C1lcDATP.js} +1 -1
  83. package/site-dist/assets/{reference_design_cli-adapter.md.pJy3x6Un.lean.js → reference_design_cli-adapter.md.C1lcDATP.lean.js} +1 -1
  84. package/site-dist/changelog.html +5 -5
  85. package/site-dist/guide/cli.html +4 -4
  86. package/site-dist/guide/dsh.html +8 -6
  87. package/site-dist/guide/getting-started.html +5 -5
  88. package/site-dist/guide/how-it-works.html +4 -4
  89. package/site-dist/guide/index.html +4 -4
  90. package/site-dist/guide/install.html +11 -9
  91. package/site-dist/guide/intranet.html +4 -4
  92. package/site-dist/guide/maintainer.html +5 -5
  93. package/site-dist/guide/mogao.html +7 -7
  94. package/site-dist/guide/phases.html +4 -4
  95. package/site-dist/guide/project.html +4 -4
  96. package/site-dist/guide/user.html +4 -4
  97. package/site-dist/guide/walkthrough.html +34 -0
  98. package/site-dist/hashmap.json +1 -1
  99. package/site-dist/index.html +4 -4
  100. package/site-dist/reference/adr/0001-new-repo-core-and-adapters.html +4 -4
  101. package/site-dist/reference/adr/0002-two-orchestration-modes.html +4 -4
  102. package/site-dist/reference/adr/0003-generate-once-then-lock.html +4 -4
  103. package/site-dist/reference/adr/0004-external-contracts-stay-stable.html +4 -4
  104. package/site-dist/reference/adr/0005-skill-names.html +4 -4
  105. package/site-dist/reference/adr/0006-deterministic-engine-platform-capabilities.html +4 -4
  106. package/site-dist/reference/adr/0007-one-install-many-repos.html +4 -4
  107. package/site-dist/reference/adr/0008-capability-sources-and-platform-plugin.html +4 -4
  108. package/site-dist/reference/adr/index.html +4 -4
  109. package/site-dist/reference/commands.html +4 -4
  110. package/site-dist/reference/config.html +4 -4
  111. package/site-dist/reference/contracts/agent-runtime.html +4 -4
  112. package/site-dist/reference/contracts/cli-json.html +5 -5
  113. package/site-dist/reference/contracts/feature-files.html +4 -4
  114. package/site-dist/reference/contracts/index.html +4 -4
  115. package/site-dist/reference/contracts/notifier-event.html +4 -4
  116. package/site-dist/reference/contracts/result-file.html +4 -4
  117. package/site-dist/reference/contracts/spec.html +4 -4
  118. package/site-dist/reference/contracts/state.html +4 -4
  119. package/site-dist/reference/contracts/usage-record.html +4 -4
  120. package/site-dist/reference/contracts/verify.html +4 -4
  121. package/site-dist/reference/design/adapter-guide.html +4 -4
  122. package/site-dist/reference/design/architecture.html +4 -4
  123. package/site-dist/reference/design/builtin-capabilities.html +6 -6
  124. package/site-dist/reference/design/cli-adapter.html +5 -5
  125. package/site-dist/reference/design/platform-vocabulary.html +4 -4
  126. package/site-dist/reference/scope.html +4 -4
  127. package/skills/laoshi/SKILL.md +1 -3
  128. package/skills/laoshi-setup/SKILL.md +1 -1
  129. package/ui/shared/view-model.ts +424 -0
  130. package/ui/web/board.ts +1126 -0
  131. package/site-dist/assets/changelog.md.BU-CvyJ1.js +0 -1
  132. package/site-dist/assets/chunks/@localSearchIndexroot.CfgJeQRO.js +0 -1
  133. package/site-dist/assets/guide_dsh.md.0X-eYB87.js +0 -5
  134. package/site-dist/assets/guide_dsh.md.0X-eYB87.lean.js +0 -5
  135. package/site-dist/assets/guide_maintainer.md.Da1ffqxm.js +0 -1
  136. package/site-dist/assets/guide_maintainer.md.Da1ffqxm.lean.js +0 -1
  137. package/site-dist/assets/reference_contracts_cli-json.md.D6vfWOD9.js +0 -1
  138. package/site-dist/assets/reference_contracts_cli-json.md.D6vfWOD9.lean.js +0 -1
  139. /package/site-dist/assets/{guide_getting-started.md.BxOxfic_.lean.js → guide_getting-started.md.BDd3nU5n.lean.js} +0 -0
@@ -0,0 +1,238 @@
1
+ // `laoshi diagnose <需求> [--out <目录>]`: collects a redacted diagnostic bundle for a requirement
2
+ // (state, pipeline log tail, step results, step agent outputs/events, sanitized config, environment)
3
+ // so users can hand one clean folder to maintainers for troubleshooting.
4
+
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { locate } from "./api.js";
10
+ import { DEFAULT_CONFIG, loadConfig, type PipelineConfig } from "./config.js";
11
+ import { defaultConfigPath, kitHome, kitVersion } from "./locations.js";
12
+ import { type PipelineState, readState, statePath } from "./state.js";
13
+
14
+ const MAX_LOG_BYTES = 200 * 1024;
15
+ const MAX_AGENT_FILE_BYTES = 64 * 1024;
16
+
17
+ /** Redacts credentials, tokens, private keys, and secret environment variables from diagnostic text. */
18
+ export function redactText(text: string): string {
19
+ return text
20
+ .replace(/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g, "-----BEGIN PRIVATE KEY-----\n***REDACTED***\n-----END PRIVATE KEY-----")
21
+ .replace(/(authorization["']?\s*[:=]\s*["']?(?:bearer\s+|basic\s+)?)[^\s"',}]+/gi, "$1***")
22
+ .replace(/\b(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi, "$1***")
23
+ .replace(/((?:token|secret|password|passwd|pwd|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|credential|cookie)[A-Za-z0-9_.-]*["']?\s*[:=]\s*["']?)[^\s"',;)}]{4,}/gi, "$1***")
24
+ .replace(/\b([A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIAL)[A-Z0-9_]*=)\S+/g, "$1***")
25
+ .replace(/\b(sk-[A-Za-z0-9_-]{16,}|gh[pous]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{12,})\b/g, "***");
26
+ }
27
+
28
+ function readTail(file: string, maxBytes: number): string | null {
29
+ if (!fs.existsSync(file)) return null;
30
+ const stat = fs.statSync(file);
31
+ if (!stat.isFile()) return null;
32
+ if (stat.size <= maxBytes) return fs.readFileSync(file, "utf8");
33
+ const fd = fs.openSync(file, "r");
34
+ try {
35
+ const buf = Buffer.alloc(maxBytes);
36
+ fs.readSync(fd, buf, 0, maxBytes, stat.size - maxBytes);
37
+ return `...[已截断前 ${stat.size - maxBytes} 字节]...\n${buf.toString("utf8")}`;
38
+ } finally {
39
+ fs.closeSync(fd);
40
+ }
41
+ }
42
+
43
+ function writeRedacted(dest: string, content: string): void {
44
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
45
+ fs.writeFileSync(dest, redactText(content), "utf8");
46
+ }
47
+
48
+ function sanitizeJson(value: unknown): unknown {
49
+ if (typeof value === "string") return redactText(value);
50
+ if (Array.isArray(value)) return value.map(sanitizeJson);
51
+ if (value && typeof value === "object") {
52
+ const out: Record<string, unknown> = {};
53
+ for (const [k, v] of Object.entries(value)) {
54
+ if (/(token|secret|password|passwd|api[_-]?key|access[_-]?key|private[_-]?key|credential|cookie)/i.test(k) && typeof v === "string" && v.length > 0) {
55
+ out[k] = "***";
56
+ } else {
57
+ out[k] = sanitizeJson(v);
58
+ }
59
+ }
60
+ return out;
61
+ }
62
+ return value;
63
+ }
64
+
65
+ function collectAgentIds(state: PipelineState | null): string[] {
66
+ if (!state) return [];
67
+ const ids = new Set<string>();
68
+ for (const step of state.history ?? []) {
69
+ if (step.agentId) ids.add(step.agentId);
70
+ }
71
+ if (state.waitingPermission?.agentId) ids.add(state.waitingPermission.agentId);
72
+ return [...ids];
73
+ }
74
+
75
+ export interface DiagnoseOptions {
76
+ repo: string;
77
+ featureDir: string;
78
+ home?: string;
79
+ config?: PipelineConfig;
80
+ configSources?: string[];
81
+ outDir?: string;
82
+ now?: Date;
83
+ }
84
+
85
+ export interface DiagnoseResult {
86
+ outDir: string;
87
+ files: string[];
88
+ agentCount: number;
89
+ }
90
+
91
+ /** Collects a redacted diagnostic bundle directory for one requirement. */
92
+ export function collectDiagnoseBundle(options: DiagnoseOptions): DiagnoseResult {
93
+ const home = options.home ?? kitHome();
94
+ const featureName = path.basename(options.featureDir);
95
+ const stamp = (options.now ?? new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
96
+ const outDir = path.resolve(options.outDir ?? path.join(home, "diagnose", `${featureName}-${stamp}`));
97
+ fs.mkdirSync(outDir, { recursive: true });
98
+
99
+ const files: string[] = [];
100
+ const record = (rel: string, content: string) => {
101
+ writeRedacted(path.join(outDir, rel), content);
102
+ files.push(rel);
103
+ };
104
+
105
+ const pipelineDir = path.join(options.repo, options.featureDir, ".pipeline");
106
+ const stateFile = statePath(options.repo, options.featureDir);
107
+ const state = readState(stateFile);
108
+ if (fs.existsSync(stateFile)) {
109
+ record("state.json", fs.readFileSync(stateFile, "utf8"));
110
+ }
111
+
112
+ const logTail = readTail(path.join(pipelineDir, "pipeline.log"), MAX_LOG_BYTES);
113
+ if (logTail !== null) {
114
+ record("pipeline.log", logTail);
115
+ }
116
+
117
+ const resultsDir = path.join(pipelineDir, "results");
118
+ if (fs.existsSync(resultsDir) && fs.statSync(resultsDir).isDirectory()) {
119
+ for (const entry of fs.readdirSync(resultsDir).sort()) {
120
+ const full = path.join(resultsDir, entry);
121
+ if (fs.statSync(full).isFile() && entry.endsWith(".json")) {
122
+ record(path.posix.join("results", entry), fs.readFileSync(full, "utf8"));
123
+ }
124
+ }
125
+ }
126
+
127
+ const adapter = state?.adapter?.id ?? options.config?.platform?.adapter ?? "default";
128
+ const agentIds = collectAgentIds(state);
129
+ let agentCount = 0;
130
+ const agentsRoot = path.join(home, adapter, "agents");
131
+ if (fs.existsSync(agentsRoot) && fs.statSync(agentsRoot).isDirectory()) {
132
+ for (const id of agentIds) {
133
+ const dir = path.join(agentsRoot, id);
134
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) continue;
135
+ agentCount++;
136
+ for (const entry of fs.readdirSync(dir).sort()) {
137
+ const full = path.join(dir, entry);
138
+ if (!fs.statSync(full).isFile()) continue;
139
+ if (entry === "agent.json" || entry === "decision.json" || entry.endsWith(".txt") || entry.endsWith(".md") || entry === "events.jsonl" || /^run-\d+\.(out|err)$/.test(entry)) {
140
+ const limit = entry === "events.jsonl" ? MAX_LOG_BYTES : MAX_AGENT_FILE_BYTES;
141
+ const text = readTail(full, limit);
142
+ if (text !== null) record(path.posix.join("agents", id, entry), text);
143
+ }
144
+ }
145
+ }
146
+ }
147
+
148
+ if (options.config) {
149
+ record("config.json", `${JSON.stringify({ sources: options.configSources ?? [], config: sanitizeJson(options.config) }, null, 2)}\n`);
150
+ }
151
+
152
+ const summary = {
153
+ generatedAt: (options.now ?? new Date()).toISOString(),
154
+ laoshiVersion: kitVersion(),
155
+ nodeVersion: process.version,
156
+ platform: `${process.platform}-${process.arch}`,
157
+ hostname: os.hostname(),
158
+ adapter,
159
+ repo: options.repo,
160
+ featureDir: options.featureDir,
161
+ state: state
162
+ ? {
163
+ status: state.status,
164
+ stopKind: state.stopKind ?? null,
165
+ stopReason: state.stopReason ? redactText(state.stopReason) : null,
166
+ outcome: state.outcome ? redactText(state.outcome) : null,
167
+ branch: state.branch,
168
+ profile: state.profile,
169
+ startedAt: state.startedAt,
170
+ updatedAt: state.updatedAt,
171
+ history: (state.history ?? []).map((s) => ({
172
+ key: s.key,
173
+ attempt: s.attempt,
174
+ outcome: s.outcome,
175
+ agentId: s.agentId,
176
+ startedAt: s.startedAt,
177
+ endedAt: s.endedAt,
178
+ error: s.error ? redactText(s.error) : null,
179
+ })),
180
+ waitingPermission: state.waitingPermission ?? null,
181
+ }
182
+ : null,
183
+ agentCount,
184
+ files: [...files, "summary.json"],
185
+ };
186
+ writeRedacted(path.join(outDir, "summary.json"), `${JSON.stringify(summary, null, 2)}\n`);
187
+ files.push("summary.json");
188
+
189
+ return { outDir, files, agentCount };
190
+ }
191
+
192
+ function parseArgs(argv: string[]): { feature: string | null; outDir?: string; help: boolean } {
193
+ let feature: string | null = null;
194
+ let outDir: string | undefined;
195
+ let help = false;
196
+ for (let i = 0; i < argv.length; i++) {
197
+ const a = argv[i];
198
+ if (a === "-h" || a === "--help") help = true;
199
+ else if (a === "--out" && argv[i + 1]) outDir = argv[++i];
200
+ else if (a.startsWith("--out=")) outDir = a.slice(6);
201
+ else if (!a.startsWith("-") && !feature) feature = a;
202
+ }
203
+ return { feature, outDir, help };
204
+ }
205
+
206
+ async function main(argv: string[]): Promise<number> {
207
+ const args = parseArgs(argv);
208
+ if (args.help || !args.feature) {
209
+ console.log("用法:laoshi diagnose <需求> [--out <目录>]");
210
+ console.log("导出已脱敏的诊断包(状态、日志尾部、步骤结果、步骤输出与事件),便于发给维护者排查问题。");
211
+ return args.help ? 0 : 2;
212
+ }
213
+ const { repo, featureDir } = locate(process.cwd(), args.feature);
214
+ let config: PipelineConfig = DEFAULT_CONFIG;
215
+ let configSources: string[] = [];
216
+ try {
217
+ const loaded = loadConfig(defaultConfigPath(), repo);
218
+ config = loaded.config;
219
+ configSources = loaded.sources;
220
+ } catch {
221
+ // Use default config when install/project config is unreadable.
222
+ }
223
+ const res = collectDiagnoseBundle({ repo, featureDir, config, configSources, outDir: args.outDir });
224
+ console.log(`已生成脱敏诊断包(${res.files.length} 个文件,含 ${res.agentCount} 个步骤记录):`);
225
+ console.log(` ${res.outDir}`);
226
+ console.log("请压缩这个目录发给维护者。");
227
+ return 0;
228
+ }
229
+
230
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
231
+ main(process.argv.slice(2)).then(
232
+ (code) => process.exit(code),
233
+ (error: Error) => {
234
+ console.error(`生成诊断包失败:${error.message}`);
235
+ process.exit(1);
236
+ },
237
+ );
238
+ }
@@ -10,7 +10,9 @@ import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { parseArgs } from "node:util";
12
12
  import { ConfigError, loadConfig, type PipelineConfig, PROJECT_CONFIG_FILE, projectConfigPath, resolveRelatedRepo } from "./config.js";
13
+ import { validateExtensions } from "./extensions.js";
13
14
  import { gitInfo } from "./git.js";
15
+ import { discoverSiblingRepos, MAX_JOINT } from "./joint.js";
14
16
  import { codebaseOf, userOf } from "./identity.js";
15
17
  import { defaultConfigPath, homeOf, KIT_ROOT, kitPackageName, kitVersion } from "./locations.js";
16
18
  import { PROJECT_DIR } from "./prompts.js";
@@ -114,11 +116,26 @@ function configuration(configPath: string, repo: string | null): PipelineConfig
114
116
  if (panel.enabled) {
115
117
  report("ok", `评审小组:${panel.members.length} 位成员,用于 ${panel.steps.join("、")}(${panel.profiles.join("、")}档,首轮)`);
116
118
  if (panel.members.length === 1) report("warn", "评审小组只有 1 位成员,效果接近单人评审", "建议配置 2–3 位,使用不同厂商的模型");
119
+ else {
120
+ const providers = new Set(panel.members.map((m) => (m.provider ? m.provider.split("/")[0] : m.platformProfile ?? "")).filter(Boolean));
121
+ if (providers.size === 1) {
122
+ report("warn", `评审小组 ${panel.members.length} 位成员来自同一提供方(${[...providers][0]}),盲区容易重叠`, "建议混配不同厂商的模型以提升互补性");
123
+ }
124
+ }
117
125
  }
118
126
  const proposals = loaded.config.designProposals;
119
127
  if (proposals.enabled) {
120
128
  report("ok", `方案提案:${proposals.members.length || "builder 和 reviewer 各"} ${proposals.members.length ? "位成员" : "一份"},用于 ${proposals.profiles.join("、")}档`);
121
129
  }
130
+ const extensions = loaded.config.extensions;
131
+ if (extensions.length > 0) {
132
+ const summary = extensions.map((e) => `${e.id}(${e.kind}@${e.after})`).join("、");
133
+ report("ok", `受控流程扩展:${extensions.length} 项(${summary})`);
134
+ if (repo) {
135
+ const check = validateExtensions(extensions, repo);
136
+ for (const err of check.errors) report("warn", `流程扩展检查:${err}`, `检查 ${path.basename(projectConfigPath(repo))} 或本机配置中的 extensions`);
137
+ }
138
+ }
122
139
  if (repo) {
123
140
  const { checks, relatedRepos } = loaded.config;
124
141
  if (checks.length > 0) {
@@ -138,6 +155,14 @@ function configuration(configPath: string, repo: string | null): PipelineConfig
138
155
  if (fs.existsSync(dir)) report("ok", `关联仓库(只读参考):${r.name} → ${dir}`);
139
156
  else report("warn", `关联仓库「${r.name}」不在这台机器上:${dir}`, "把它克隆到这个位置;或修改 relatedRepos 中的路径(相对项目目录,团队约定把相关仓库放在同一个上级目录最方便)");
140
157
  }
158
+ if (loaded.config.maxJointRepos !== MAX_JOINT) {
159
+ report("ok", `联合开发上限(maxJointRepos):最多再涉及 ${loaded.config.maxJointRepos} 个仓库`);
160
+ }
161
+ const siblings = discoverSiblingRepos(repo, relatedRepos);
162
+ if (siblings.length > 0 && relatedRepos.length === 0) {
163
+ const preview = siblings.slice(0, 5).map((s) => `${s.name}(${s.path})`).join("、");
164
+ info(`发现同级 git 仓库:${preview}${siblings.length > 5 ? ` 等 ${siblings.length} 个` : ""};如需多仓参考或联调,可运行 /laoshi-setup 自动登记到 relatedRepos`);
165
+ }
141
166
  }
142
167
  const push = loaded.config.push;
143
168
  if (push.enabled) {
@@ -66,6 +66,17 @@ export function typicalLine(t: Typical | null): string | null {
66
66
  return `参考:本机最近 ${t.basis} 个${PROFILE_NAMES[t.profile] ?? t.profile}需求,agent 合计用时中位数约 ${minutesText(t.agentMinutes)}${t.tokens !== null ? `,约 ${tokenText(t.tokens)} tokens` : ""}(不含等人确认的时间)。`;
67
67
  }
68
68
 
69
+ /** Pre-run budget heads-up when historical median tokens already approach or exceed budget.tokens. */
70
+ export function budgetWarnLine(
71
+ t: Typical | null,
72
+ budget: { tokens: number | null; warnPercent: number },
73
+ ): string | null {
74
+ if (!t || t.tokens === null || budget.tokens === null || budget.tokens <= 0) return null;
75
+ const pct = Math.round((t.tokens / budget.tokens) * 100);
76
+ if (pct < budget.warnPercent) return null;
77
+ return `预算提醒:同类${PROFILE_NAMES[t.profile] ?? t.profile}需求中位数约 ${tokenText(t.tokens)} tokens,已达当前单需求预算(${tokenText(budget.tokens)})的 ${pct}%;运行中到达预算上限会暂停确认是否继续。`;
78
+ }
79
+
69
80
  export interface Progress {
70
81
  usedAgentMinutes: number;
71
82
  usedTokens: number | null;
@@ -0,0 +1,271 @@
1
+ // Controlled flow extensions (M3): preserves the core pipeline skeleton and stages,
2
+ // while letting install-level or project-level config attach custom extra steps after
3
+ // fixed lifecycle hooks. Supports two task kinds:
4
+ // - "ai": runs a step agent with a skill file and/or prompt text
5
+ // - "script": runs a shell command (never PowerShell on Windows) and logs its output
6
+
7
+ import { spawnSync } from "node:child_process";
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import type { ProfileName, RequirementType } from "./config.js";
11
+
12
+ export const EXTENSION_HOOKS = [
13
+ "design",
14
+ "design_review",
15
+ "implement",
16
+ "code_review",
17
+ "handoff",
18
+ "verify",
19
+ "report",
20
+ ] as const;
21
+
22
+ export type ExtensionHook = (typeof EXTENSION_HOOKS)[number];
23
+
24
+ export type ExtensionRequirementType = RequirementType | "feature";
25
+
26
+ export interface ExtensionBase {
27
+ /** Unique identifier (lowercase ASCII, digits, - or _), e.g. "test-cases" or "archive-build". */
28
+ id: string;
29
+ /** Human-readable title shown in logs and status. */
30
+ title: string;
31
+ /** Fixed core stage after which this extension runs. */
32
+ after: ExtensionHook;
33
+ /** Optional profile filter; runs on all profiles when omitted. */
34
+ profiles?: ProfileName[];
35
+ /** Optional requirement type filter ("feature" matches standard requirements); runs on all types when omitted. */
36
+ types?: ExtensionRequirementType[];
37
+ /** "fail" (default) stops the pipeline on failure; "warn" logs a warning and continues. */
38
+ onFailure?: "warn" | "fail";
39
+ }
40
+
41
+ export interface AiExtensionStep extends ExtensionBase {
42
+ kind: "ai";
43
+ role?: "builder" | "reviewer";
44
+ /** Path to a skill directory (containing SKILL.md) or markdown file, relative to repo or absolute. */
45
+ skill?: string;
46
+ /** Prompt instructions appended after the skill (at least one of skill or prompt is required). */
47
+ prompt?: string;
48
+ timeoutMinutes?: number;
49
+ }
50
+
51
+ export interface ScriptExtensionStep extends ExtensionBase {
52
+ kind: "script";
53
+ /** Shell command to execute. */
54
+ command: string;
55
+ /** Working directory relative to repo root (defaults to repo root). */
56
+ cwd?: string;
57
+ timeoutSeconds?: number;
58
+ }
59
+
60
+ export type ExtensionStep = AiExtensionStep | ScriptExtensionStep;
61
+
62
+ const ID_RE = /^[a-z0-9][a-z0-9_-]{0,48}$/;
63
+ const PROFILES: readonly string[] = ["quick", "standard"];
64
+ const TYPES: readonly string[] = ["feature", "defect", "refactor", "assessment"];
65
+
66
+ function isRecord(v: unknown): v is Record<string, unknown> {
67
+ return typeof v === "object" && v !== null && !Array.isArray(v);
68
+ }
69
+
70
+ /** Resolves a skill path (file or directory containing SKILL.md). */
71
+ export function resolveSkillFile(skillPath: string, repoDir?: string): string {
72
+ const base = path.isAbsolute(skillPath) ? skillPath : path.resolve(repoDir ?? process.cwd(), skillPath);
73
+ if (fs.existsSync(base) && fs.statSync(base).isDirectory()) {
74
+ return path.join(base, "SKILL.md");
75
+ }
76
+ return base;
77
+ }
78
+
79
+ /** Validates raw `extensions` config array, returning normalized entries and any validation errors. */
80
+ export function validateExtensions(raw: unknown, repoDir?: string): { extensions: ExtensionStep[]; errors: string[] } {
81
+ if (raw === undefined || raw === null) return { extensions: [], errors: [] };
82
+ if (!Array.isArray(raw)) return { extensions: [], errors: ["extensions 必须是数组"] };
83
+
84
+ const extensions: ExtensionStep[] = [];
85
+ const errors: string[] = [];
86
+ const seen = new Set<string>();
87
+
88
+ raw.forEach((item, i) => {
89
+ const prefix = `extensions[${i}]`;
90
+ if (!isRecord(item)) {
91
+ errors.push(`${prefix} 必须是对象`);
92
+ return;
93
+ }
94
+ const id = typeof item.id === "string" ? item.id.trim() : "";
95
+ if (!ID_RE.test(id)) errors.push(`${prefix}.id 必须是小写字母/数字开头,仅含 a-z、0-9、-、_`);
96
+ else if (seen.has(id)) errors.push(`${prefix}.id 重复:${id}`);
97
+ else seen.add(id);
98
+
99
+ const title = typeof item.title === "string" ? item.title.trim() : "";
100
+ if (!title) errors.push(`${prefix}.title 不能为空`);
101
+
102
+ const after = typeof item.after === "string" ? item.after.trim() : "";
103
+ if (!(EXTENSION_HOOKS as readonly string[]).includes(after)) {
104
+ errors.push(`${prefix}.after 必须是 ${EXTENSION_HOOKS.join("、")} 之一`);
105
+ }
106
+
107
+ const kind = item.kind;
108
+ if (kind !== "ai" && kind !== "script") {
109
+ errors.push(`${prefix}.kind 必须是 "ai" 或 "script"`);
110
+ return;
111
+ }
112
+
113
+ const onFailure = item.onFailure ?? "fail";
114
+ if (onFailure !== "fail" && onFailure !== "warn") {
115
+ errors.push(`${prefix}.onFailure 必须是 "fail" 或 "warn"`);
116
+ }
117
+
118
+ let profiles: ProfileName[] | undefined;
119
+ if (item.profiles !== undefined) {
120
+ if (!Array.isArray(item.profiles) || !item.profiles.every((p) => typeof p === "string" && PROFILES.includes(p))) {
121
+ errors.push(`${prefix}.profiles 只能包含 ${PROFILES.join("、")}`);
122
+ } else {
123
+ profiles = item.profiles as ProfileName[];
124
+ }
125
+ }
126
+
127
+ let types: ExtensionRequirementType[] | undefined;
128
+ if (item.types !== undefined) {
129
+ if (!Array.isArray(item.types) || !item.types.every((t) => typeof t === "string" && TYPES.includes(t))) {
130
+ errors.push(`${prefix}.types 只能包含 ${TYPES.join("、")}`);
131
+ } else {
132
+ types = item.types as ExtensionRequirementType[];
133
+ }
134
+ }
135
+
136
+ if (kind === "ai") {
137
+ const role = item.role ?? "builder";
138
+ if (role !== "builder" && role !== "reviewer") errors.push(`${prefix}.role 必须是 "builder" 或 "reviewer"`);
139
+ const skill = typeof item.skill === "string" && item.skill.trim() ? item.skill.trim() : undefined;
140
+ const prompt = typeof item.prompt === "string" && item.prompt.trim() ? item.prompt.trim() : undefined;
141
+ if (!skill && !prompt) errors.push(`${prefix}(ai 类型)至少需要配置 skill 或 prompt`);
142
+ if (skill && repoDir) {
143
+ const resolved = resolveSkillFile(skill, repoDir);
144
+ if (!fs.existsSync(resolved)) errors.push(`${prefix}.skill 指向的文件不存在:${resolved}`);
145
+ }
146
+ const timeoutMinutes = item.timeoutMinutes !== undefined ? Number(item.timeoutMinutes) : undefined;
147
+ if (timeoutMinutes !== undefined && (!Number.isFinite(timeoutMinutes) || timeoutMinutes <= 0)) {
148
+ errors.push(`${prefix}.timeoutMinutes 必须是正数`);
149
+ }
150
+ extensions.push({
151
+ id,
152
+ title,
153
+ after: after as ExtensionHook,
154
+ kind: "ai",
155
+ role: role === "reviewer" ? "reviewer" : "builder",
156
+ ...(skill ? { skill } : {}),
157
+ ...(prompt ? { prompt } : {}),
158
+ ...(profiles ? { profiles } : {}),
159
+ ...(types ? { types } : {}),
160
+ ...(timeoutMinutes ? { timeoutMinutes } : {}),
161
+ onFailure: onFailure === "warn" ? "warn" : "fail",
162
+ });
163
+ } else {
164
+ const command = typeof item.command === "string" ? item.command.trim() : "";
165
+ if (!command) errors.push(`${prefix}.command 不能为空`);
166
+ const cwd = typeof item.cwd === "string" && item.cwd.trim() ? item.cwd.trim() : undefined;
167
+ const timeoutSeconds = item.timeoutSeconds !== undefined ? Number(item.timeoutSeconds) : 180;
168
+ if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
169
+ errors.push(`${prefix}.timeoutSeconds 必须是正数`);
170
+ }
171
+ extensions.push({
172
+ id,
173
+ title,
174
+ after: after as ExtensionHook,
175
+ kind: "script",
176
+ command,
177
+ ...(cwd ? { cwd } : {}),
178
+ ...(profiles ? { profiles } : {}),
179
+ ...(types ? { types } : {}),
180
+ timeoutSeconds,
181
+ onFailure: onFailure === "warn" ? "warn" : "fail",
182
+ });
183
+ }
184
+ });
185
+
186
+ return { extensions, errors };
187
+ }
188
+
189
+ /** Merges install-level and project-level extensions by id (project overrides same id, appends new). */
190
+ export function mergeExtensions(base: ExtensionStep[], override: ExtensionStep[]): ExtensionStep[] {
191
+ const byId = new Map<string, ExtensionStep>();
192
+ for (const step of base) byId.set(step.id, step);
193
+ for (const step of override) byId.set(step.id, step);
194
+ return [...byId.values()];
195
+ }
196
+
197
+ /** Selects extensions applicable to a specific hook, profile, and requirement type. */
198
+ export function selectExtensions(
199
+ extensions: ExtensionStep[],
200
+ ctx: { after: ExtensionHook; profile: ProfileName; type?: ExtensionRequirementType | null },
201
+ ): ExtensionStep[] {
202
+ const effectiveType: ExtensionRequirementType = ctx.type ?? "feature";
203
+ return extensions.filter((step) => {
204
+ if (step.after !== ctx.after) return false;
205
+ if (step.profiles && step.profiles.length > 0 && !step.profiles.includes(ctx.profile)) return false;
206
+ if (step.types && step.types.length > 0 && !step.types.includes(effectiveType)) return false;
207
+ return true;
208
+ });
209
+ }
210
+
211
+ export interface ScriptExtensionResult {
212
+ ok: boolean;
213
+ exitCode: number | null;
214
+ output: string;
215
+ logFile: string;
216
+ }
217
+
218
+ /** Executes a script extension step and saves its output to `.pipeline/extensions/<id>.log`. */
219
+ export function runScriptExtension(
220
+ step: ScriptExtensionStep,
221
+ input: { repo: string; featureDir: string; env?: NodeJS.ProcessEnv },
222
+ ): ScriptExtensionResult {
223
+ const cwd = step.cwd ? path.resolve(input.repo, step.cwd) : input.repo;
224
+ const env: NodeJS.ProcessEnv = {
225
+ ...(input.env ?? process.env),
226
+ LAOSHI_REPO: input.repo,
227
+ LAOSHI_FEATURE_DIR: input.featureDir,
228
+ LAOSHI_EXTENSION_ID: step.id,
229
+ LAOSHI_HOOK: step.after,
230
+ };
231
+ const timeout = (step.timeoutSeconds ?? 180) * 1000;
232
+ // shell: true runs cmd.exe /d /s /c with verbatim arguments on Windows (never PowerShell) and /bin/sh -c on POSIX.
233
+ const r = spawnSync(step.command, { cwd, env, encoding: "utf8", timeout, shell: true, windowsHide: true });
234
+
235
+ const output = [r.stdout ?? "", r.stderr ?? "", r.error ? `ERROR: ${r.error.message}` : ""].filter(Boolean).join("\n").trim();
236
+ const logFile = path.join(input.repo, input.featureDir, ".pipeline", "extensions", `${step.id}.log`);
237
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
238
+ fs.writeFileSync(
239
+ logFile,
240
+ [`# ${step.title} (${step.id})`, `hook: ${step.after}`, `command: ${step.command}`, `cwd: ${cwd}`, `exitCode: ${r.status ?? "null"}`, "", output, ""].join("\n"),
241
+ "utf8",
242
+ );
243
+ return { ok: r.status === 0 && !r.error, exitCode: r.status, output, logFile };
244
+ }
245
+
246
+ /** Builds the complete prompt for an AI/skill extension step. */
247
+ export function buildAiExtensionPrompt(step: AiExtensionStep, input: { repo: string; featureDir: string }): string {
248
+ const parts: string[] = [
249
+ `# 扩展步骤:${step.title}(${step.id})`,
250
+ "",
251
+ "<pipeline-context>",
252
+ `- 仓库目录:${input.repo}`,
253
+ `- 功能目录:${input.featureDir}`,
254
+ `- 触发阶段:${step.after} 之后`,
255
+ "</pipeline-context>",
256
+ "",
257
+ ];
258
+ if (step.skill) {
259
+ const file = resolveSkillFile(step.skill, input.repo);
260
+ if (fs.existsSync(file)) {
261
+ parts.push("## 关联 Skill 说明", "", fs.readFileSync(file, "utf8").trim(), "");
262
+ } else {
263
+ parts.push(`(提示:未能读取 skill 文件 ${file},请按下方任务说明执行。)`, "");
264
+ }
265
+ }
266
+ if (step.prompt) {
267
+ parts.push("## 任务说明", "", step.prompt.trim(), "");
268
+ }
269
+ parts.push("完成后请直接总结产出与结论;不要修改无关文件。");
270
+ return parts.join("\n");
271
+ }
@@ -0,0 +1,47 @@
1
+ // `req handover <需求> <接手人> [--note <说明>] [--repo <目录>]` (X5):
2
+ // transfers ownership of a requirement to another colleague and records `.pipeline/owner.json`.
3
+ import path from "node:path";
4
+ import { locate } from "./api.js";
5
+ import { handover } from "./handover.js";
6
+
7
+ function main(argvIn: string[]): number {
8
+ if (argvIn.includes("--help") || argvIn.includes("-h")) {
9
+ console.log("用法:laoshi handover <需求> <接手人> [--note <说明>] [--repo <目录>]");
10
+ return 0;
11
+ }
12
+ const argv = [...argvIn];
13
+ let repoArg = process.cwd();
14
+ let note: string | null = null;
15
+ const positional: string[] = [];
16
+
17
+ for (let i = 0; i < argv.length; i++) {
18
+ const a = argv[i];
19
+ if (a === "--note" && argv[i + 1] !== undefined) note = argv[++i];
20
+ else if (a.startsWith("--note=")) note = a.slice(7);
21
+ else if (a === "--repo" && argv[i + 1] !== undefined) repoArg = path.resolve(argv[++i]);
22
+ else if (a.startsWith("--repo=")) repoArg = path.resolve(a.slice(7));
23
+ else if (!a.startsWith("-")) positional.push(a);
24
+ else {
25
+ console.error(`未知选项:${a}`);
26
+ return 2;
27
+ }
28
+ }
29
+
30
+ const [feature, to] = positional;
31
+ if (!feature || !to || positional.length > 2) {
32
+ console.error("用法:laoshi handover <需求> <接手人> [--note <说明>]");
33
+ return 2;
34
+ }
35
+
36
+ const { repo, featureDir } = locate(repoArg, feature);
37
+ const record = handover(path.join(repo, featureDir), { to, note });
38
+ console.log(`已把 ${featureDir} 转给 ${record.owner}${note?.trim() ? `(说明:${note.trim()})` : ""}`);
39
+ return 0;
40
+ }
41
+
42
+ try {
43
+ process.exit(main(process.argv.slice(2)));
44
+ } catch (error) {
45
+ console.error(`转交失败:${(error as Error).message}`);
46
+ process.exit(1);
47
+ }