@yiyi_zhang/laoshi 0.2.0 → 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 (113) hide show
  1. package/CHANGELOG.md +21 -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 +9 -1
  9. package/adapters/mogao/mogao-runtime.ts +30 -8
  10. package/adapters/paseo/install.mjs +13 -4
  11. package/adapters/paseo/plugin/client/data.ts +13 -2
  12. package/adapters/paseo/plugin/client/detail.tsx +244 -4
  13. package/adapters/paseo/plugin/client/format.ts +25 -117
  14. package/adapters/paseo/plugin/client/overview.tsx +3 -3
  15. package/adapters/paseo/plugin/index.server.ts +2 -1
  16. package/adapters/paseo/plugin/package.json +1 -1
  17. package/adapters/paseo/plugin/paseo-plugin.json +1 -1
  18. package/adapters/paseo/plugin/server/handlers.ts +22 -4
  19. package/adapters/paseo/plugin/server/req.ts +17 -4
  20. package/adapters/paseo/plugin/shared/contracts.ts +28 -2
  21. package/adapters/paseo/plugin/shared/view-model.ts +425 -0
  22. package/bin/req.mjs +10 -0
  23. package/contracts/cli-json.md +3 -1
  24. package/docs/design/dsh-adapter.md +9 -9
  25. package/docs/design/shared-ui.md +43 -0
  26. package/docs/guide//345/256/211/350/243/205/344/270/216/345/215/207/347/272/247.md +13 -8
  27. package/docs/guide//347/234/237/345/256/236/347/216/257/345/242/203/350/265/260/346/237/245.md +78 -0
  28. package/engine/src/api.ts +11 -2
  29. package/engine/src/board.ts +435 -0
  30. package/engine/src/config.ts +23 -0
  31. package/engine/src/doctor.ts +25 -0
  32. package/engine/src/estimate.ts +11 -0
  33. package/engine/src/extensions.ts +271 -0
  34. package/engine/src/handover-cmd.ts +47 -0
  35. package/engine/src/handover.ts +89 -0
  36. package/engine/src/history.ts +102 -0
  37. package/engine/src/joint.ts +49 -4
  38. package/engine/src/launch.ts +2 -1
  39. package/engine/src/main.ts +1 -1
  40. package/engine/src/messages.ts +58 -0
  41. package/engine/src/pipeline.ts +109 -4
  42. package/engine/src/reply.ts +27 -6
  43. package/engine/src/semver.ts +21 -0
  44. package/package.json +5 -2
  45. package/site-dist/404.html +2 -2
  46. package/site-dist/assets/{app.BxNgGFu-.js → app.DZpVs0VH.js} +1 -1
  47. package/site-dist/assets/changelog.md.CdUYbro4.js +1 -0
  48. package/site-dist/assets/{changelog.md.D0PzSXw9.lean.js → changelog.md.CdUYbro4.lean.js} +1 -1
  49. package/site-dist/assets/chunks/@localSearchIndexroot.CHr-ITwS.js +1 -0
  50. package/site-dist/assets/chunks/{VPLocalSearchBox.Dw_fzw9V.js → VPLocalSearchBox.BHkmziy1.js} +1 -1
  51. package/site-dist/assets/chunks/{theme.CwrnT4KI.js → theme.BsPChbDE.js} +2 -2
  52. package/site-dist/assets/guide_dsh.md.D0XhcUHz.js +7 -0
  53. package/site-dist/assets/guide_dsh.md.D0XhcUHz.lean.js +7 -0
  54. package/site-dist/assets/{guide_getting-started.md.CjzysdDe.js → guide_getting-started.md.BDd3nU5n.js} +1 -1
  55. package/site-dist/assets/{guide_install.md.By4WxsJG.js → guide_install.md.SsIHMfUu.js} +7 -5
  56. package/site-dist/assets/{guide_install.md.By4WxsJG.lean.js → guide_install.md.SsIHMfUu.lean.js} +7 -5
  57. package/site-dist/assets/guide_walkthrough.md.nj_PWP9Y.js +5 -0
  58. package/site-dist/assets/guide_walkthrough.md.nj_PWP9Y.lean.js +5 -0
  59. package/site-dist/assets/reference_contracts_cli-json.md.3iU9h4rw.js +1 -0
  60. package/site-dist/assets/reference_contracts_cli-json.md.3iU9h4rw.lean.js +1 -0
  61. package/site-dist/changelog.html +5 -5
  62. package/site-dist/guide/cli.html +4 -4
  63. package/site-dist/guide/dsh.html +8 -6
  64. package/site-dist/guide/getting-started.html +5 -5
  65. package/site-dist/guide/how-it-works.html +4 -4
  66. package/site-dist/guide/index.html +4 -4
  67. package/site-dist/guide/install.html +11 -9
  68. package/site-dist/guide/intranet.html +4 -4
  69. package/site-dist/guide/maintainer.html +4 -4
  70. package/site-dist/guide/mogao.html +4 -4
  71. package/site-dist/guide/phases.html +4 -4
  72. package/site-dist/guide/project.html +4 -4
  73. package/site-dist/guide/user.html +4 -4
  74. package/site-dist/guide/walkthrough.html +34 -0
  75. package/site-dist/hashmap.json +1 -1
  76. package/site-dist/index.html +4 -4
  77. package/site-dist/reference/adr/0001-new-repo-core-and-adapters.html +4 -4
  78. package/site-dist/reference/adr/0002-two-orchestration-modes.html +4 -4
  79. package/site-dist/reference/adr/0003-generate-once-then-lock.html +4 -4
  80. package/site-dist/reference/adr/0004-external-contracts-stay-stable.html +4 -4
  81. package/site-dist/reference/adr/0005-skill-names.html +4 -4
  82. package/site-dist/reference/adr/0006-deterministic-engine-platform-capabilities.html +4 -4
  83. package/site-dist/reference/adr/0007-one-install-many-repos.html +4 -4
  84. package/site-dist/reference/adr/0008-capability-sources-and-platform-plugin.html +4 -4
  85. package/site-dist/reference/adr/index.html +4 -4
  86. package/site-dist/reference/commands.html +4 -4
  87. package/site-dist/reference/config.html +4 -4
  88. package/site-dist/reference/contracts/agent-runtime.html +4 -4
  89. package/site-dist/reference/contracts/cli-json.html +5 -5
  90. package/site-dist/reference/contracts/feature-files.html +4 -4
  91. package/site-dist/reference/contracts/index.html +4 -4
  92. package/site-dist/reference/contracts/notifier-event.html +4 -4
  93. package/site-dist/reference/contracts/result-file.html +4 -4
  94. package/site-dist/reference/contracts/spec.html +4 -4
  95. package/site-dist/reference/contracts/state.html +4 -4
  96. package/site-dist/reference/contracts/usage-record.html +4 -4
  97. package/site-dist/reference/contracts/verify.html +4 -4
  98. package/site-dist/reference/design/adapter-guide.html +4 -4
  99. package/site-dist/reference/design/architecture.html +4 -4
  100. package/site-dist/reference/design/builtin-capabilities.html +4 -4
  101. package/site-dist/reference/design/cli-adapter.html +4 -4
  102. package/site-dist/reference/design/platform-vocabulary.html +4 -4
  103. package/site-dist/reference/scope.html +4 -4
  104. package/skills/laoshi-setup/SKILL.md +1 -1
  105. package/ui/shared/view-model.ts +424 -0
  106. package/ui/web/board.ts +1126 -0
  107. package/site-dist/assets/changelog.md.D0PzSXw9.js +0 -1
  108. package/site-dist/assets/chunks/@localSearchIndexroot.vA-yiw-8.js +0 -1
  109. package/site-dist/assets/guide_dsh.md.0X-eYB87.js +0 -5
  110. package/site-dist/assets/guide_dsh.md.0X-eYB87.lean.js +0 -5
  111. package/site-dist/assets/reference_contracts_cli-json.md.D6vfWOD9.js +0 -1
  112. package/site-dist/assets/reference_contracts_cli-json.md.D6vfWOD9.lean.js +0 -1
  113. /package/site-dist/assets/{guide_getting-started.md.CjzysdDe.lean.js → guide_getting-started.md.BDd3nU5n.lean.js} +0 -0
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { type ExtensionStep, mergeExtensions, validateExtensions } from "./extensions.js";
4
5
  import { type IntegrationConfig, validateIntegrations } from "./integrations.js";
5
6
  import { NOTIFIER_EVENT_TYPES, type NotifierConfig } from "./notifiers.js";
6
7
  import type { StepId } from "./steps.js";
@@ -316,6 +317,8 @@ export interface PipelineConfig {
316
317
  slices: { profiles: ProfileName[]; max: number };
317
318
  /** Repositories the steps may read for reference, never change. */
318
319
  relatedRepos: RelatedRepo[];
320
+ /** Maximum number of additional joint repositories in one requirement (default 2, up to 10). */
321
+ maxJointRepos: number;
319
322
  /**
320
323
  * Design confirmation point (1.8): after the design review, show the requester what they
321
324
  * will get (preview.md, a prototype for UI changes) and wait for "yes" before writing code.
@@ -329,6 +332,11 @@ export interface PipelineConfig {
329
332
  * in parallel; the reviewer consolidates. A configured review panel takes precedence.
330
333
  */
331
334
  reviewAxes: { enabled: boolean; profiles: ProfileName[] };
335
+ /**
336
+ * Controlled flow extensions (M3): custom AI/skill or shell script steps attached after
337
+ * fixed core stages, without altering the core pipeline skeleton.
338
+ */
339
+ extensions: ExtensionStep[];
332
340
  }
333
341
 
334
342
  export const DEFAULT_CONFIG: PipelineConfig = {
@@ -404,8 +412,10 @@ export const DEFAULT_CONFIG: PipelineConfig = {
404
412
  qualityGate: { fixAttempts: 2, timeoutMinutes: 20 },
405
413
  slices: { profiles: ["standard"], max: 6 },
406
414
  relatedRepos: [],
415
+ maxJointRepos: 2,
407
416
  designApproval: { mode: "ui", profiles: ["standard"], autoContinueHours: 0 },
408
417
  reviewAxes: { enabled: true, profiles: ["standard"] },
418
+ extensions: [],
409
419
  };
410
420
 
411
421
  /** Project file, at the repository root, that overrides the install-level configuration (laoshi M2c). */
@@ -547,6 +557,14 @@ function merge(base: PipelineConfig, raw: Record<string, unknown>): PipelineConf
547
557
  ...(isRecord(raw.designApproval) ? (raw.designApproval as Partial<PipelineConfig["designApproval"]>) : {}),
548
558
  };
549
559
  merged.reviewAxes = { ...base.reviewAxes, ...(isRecord(raw.reviewAxes) ? (raw.reviewAxes as Partial<PipelineConfig["reviewAxes"]>) : {}) };
560
+ if (raw.extensions !== undefined) {
561
+ if (Array.isArray(raw.extensions) && Array.isArray(base.extensions)) {
562
+ const checked = validateExtensions(raw.extensions);
563
+ merged.extensions = checked.errors.length === 0 ? mergeExtensions(base.extensions, checked.extensions) : (raw.extensions as ExtensionStep[]);
564
+ } else {
565
+ merged.extensions = raw.extensions as ExtensionStep[];
566
+ }
567
+ }
550
568
  delete (merged as unknown as Record<string, unknown>).rounds;
551
569
  return merged;
552
570
  }
@@ -644,6 +662,9 @@ function validateChecks(config: PipelineConfig): void {
644
662
  if (typeof r.path !== "string" || r.path.trim() === "") throw new ConfigError(`relatedRepos[${i}].path 必须是这台机器上的目录`);
645
663
  if (r.role !== undefined && typeof r.role !== "string") throw new ConfigError(`relatedRepos[${i}].role 必须是字符串`);
646
664
  });
665
+ if (!Number.isInteger(config.maxJointRepos) || config.maxJointRepos < 1 || config.maxJointRepos > 10) {
666
+ throw new ConfigError("maxJointRepos 必须是 1 到 10 之间的整数");
667
+ }
647
668
  }
648
669
 
649
670
  /** Where a related repository is on this machine; relative paths start from the project's checkout. */
@@ -772,6 +793,8 @@ function validate(config: PipelineConfig): void {
772
793
  }
773
794
  validatePhases(config.phases);
774
795
  validateChecks(config);
796
+ const extCheck = validateExtensions(config.extensions);
797
+ if (extCheck.errors.length > 0) throw new ConfigError(extCheck.errors.join(";"));
775
798
  for (const key of ["waitChunkSeconds", "permissionPollSeconds", "serviceReadySeconds", "queuePollSeconds"] as const) {
776
799
  if (typeof config[key] !== "number" || config[key] <= 0) throw new ConfigError(`${key} 必须是正数`);
777
800
  }
@@ -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
+ }
@@ -0,0 +1,89 @@
1
+ // Requirement handover (X5): transfers the current owner of a requirement and keeps an audit trail
2
+ // in <featureAbs>/.pipeline/owner.json (local runtime metadata, never committed).
3
+
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { userOf } from "./identity.js";
7
+ import { readState, replaceFile } from "./state.js";
8
+
9
+ export interface HandoverEvent {
10
+ from: string | null;
11
+ to: string;
12
+ at: string;
13
+ note: string | null;
14
+ }
15
+
16
+ export interface OwnerRecord {
17
+ owner: string | null;
18
+ history: HandoverEvent[];
19
+ }
20
+
21
+ export function ownerPath(featureAbs: string): string {
22
+ return path.join(featureAbs, ".pipeline", "owner.json");
23
+ }
24
+
25
+ /** Reads the current owner and handover history; returns an empty record when absent. */
26
+ export function readOwner(featureAbs: string): OwnerRecord {
27
+ const file = ownerPath(featureAbs);
28
+ if (!fs.existsSync(file)) return { owner: null, history: [] };
29
+ try {
30
+ const raw = JSON.parse(fs.readFileSync(file, "utf8")) as Partial<OwnerRecord>;
31
+ const owner = typeof raw.owner === "string" && raw.owner.trim() ? raw.owner.trim() : null;
32
+ const history = Array.isArray(raw.history)
33
+ ? raw.history.filter(
34
+ (h): h is HandoverEvent =>
35
+ typeof h === "object" && h !== null && typeof h.to === "string" && typeof h.at === "string",
36
+ )
37
+ : [];
38
+ return { owner, history };
39
+ } catch {
40
+ return { owner: null, history: [] };
41
+ }
42
+ }
43
+
44
+ /** Transfers the requirement to `to`, recording `from`, timestamp and optional note. */
45
+ export function handover(
46
+ featureAbs: string,
47
+ input: { to: string; note?: string | null; from?: string | null },
48
+ ): OwnerRecord {
49
+ const to = input.to.trim();
50
+ if (!to) throw new Error("接手人不能为空");
51
+ if (to.length > 64) throw new Error("接手人名称不能超过 64 个字符");
52
+
53
+ const current = readOwner(featureAbs);
54
+ let from = input.from !== undefined ? (input.from?.trim() || null) : current.owner;
55
+ if (from === undefined || (from === null && input.from === undefined)) {
56
+ let startedBy: string | null = null;
57
+ try {
58
+ startedBy = readState(path.join(featureAbs, ".pipeline", "state.json"))?.startedBy ?? null;
59
+ } catch {
60
+ startedBy = null;
61
+ }
62
+ from = startedBy ?? userOf();
63
+ }
64
+
65
+ const note = input.note?.trim() ? input.note.trim().slice(0, 500) : null;
66
+ const next: OwnerRecord = {
67
+ owner: to,
68
+ history: [
69
+ ...current.history,
70
+ {
71
+ from: from ?? null,
72
+ to,
73
+ at: new Date().toISOString(),
74
+ note,
75
+ },
76
+ ],
77
+ };
78
+
79
+ const dir = path.join(featureAbs, ".pipeline");
80
+ fs.mkdirSync(dir, { recursive: true });
81
+ const ignore = path.join(dir, ".gitignore");
82
+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, "*\n");
83
+
84
+ const file = ownerPath(featureAbs);
85
+ const tmp = `${file}.${process.pid}.tmp`;
86
+ fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, "utf8");
87
+ replaceFile(tmp, file);
88
+ return next;
89
+ }
@@ -0,0 +1,102 @@
1
+ // Requirement change history (X5): reads spec version, parsed changes.md entries,
2
+ // git history/diffs of spec.md, and handover/ownership metadata for one requirement.
3
+
4
+ import { spawnSync } from "node:child_process";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { locate } from "./api.js";
8
+ import { type OwnerRecord, readOwner } from "./handover.js";
9
+
10
+ const MAX_DIFF_CHARS = 20_000;
11
+
12
+ export interface ChangeEntry {
13
+ title: string;
14
+ body: string;
15
+ }
16
+
17
+ export interface SpecCommit {
18
+ commit: string;
19
+ date: string;
20
+ author: string;
21
+ subject: string;
22
+ diff: string;
23
+ truncated: boolean;
24
+ }
25
+
26
+ export interface RequirementHistory {
27
+ specVersion: string | null;
28
+ changes: ChangeEntry[];
29
+ commits: SpecCommit[];
30
+ owner: OwnerRecord;
31
+ }
32
+
33
+ /** Extracts spec version from header lines such as "- 版本:2" or "版本:2". */
34
+ export function parseSpecVersion(content: string): string | null {
35
+ const m = /^(?:-\s*)?版本\s*[::]\s*(.+)$/m.exec(content);
36
+ return m?.[1]?.trim() || null;
37
+ }
38
+
39
+ /** Splits changes.md by "## " headings, returning up to `max` entries newest-first. */
40
+ export function parseChanges(content: string, max = 50): ChangeEntry[] {
41
+ const lines = content.split(/\r?\n/);
42
+ const entries: Array<{ title: string; bodyLines: string[] }> = [];
43
+ for (const line of lines) {
44
+ if (line.startsWith("## ")) {
45
+ entries.push({ title: line.slice(3).trim(), bodyLines: [] });
46
+ } else if (entries.length > 0) {
47
+ entries[entries.length - 1].bodyLines.push(line);
48
+ }
49
+ }
50
+ return entries
51
+ .map((e) => ({ title: e.title, body: e.bodyLines.join("\n").trim() }))
52
+ .slice(-max)
53
+ .reverse();
54
+ }
55
+
56
+ function readGitHistory(repo: string, posixSpec: string): SpecCommit[] {
57
+ const logRes = spawnSync(
58
+ "git",
59
+ ["log", "-n", "10", "--format=%H%x1f%aI%x1f%an%x1f%s", "--", posixSpec],
60
+ { cwd: repo, encoding: "utf8", windowsHide: true },
61
+ );
62
+ if (logRes.status !== 0 || !logRes.stdout) return [];
63
+
64
+ const commits: SpecCommit[] = [];
65
+ for (const line of logRes.stdout.split(/\r?\n/)) {
66
+ if (!line.trim()) continue;
67
+ const [commit, date = "", author = "", subject = ""] = line.split("\x1f");
68
+ if (!commit) continue;
69
+ const showRes = spawnSync(
70
+ "git",
71
+ ["show", "--format=", "--unified=3", commit, "--", posixSpec],
72
+ { cwd: repo, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 },
73
+ );
74
+ const raw = showRes.status === 0 ? (showRes.stdout ?? "").trimEnd() : "";
75
+ const truncated = raw.length > MAX_DIFF_CHARS;
76
+ commits.push({
77
+ commit,
78
+ date,
79
+ author,
80
+ subject,
81
+ diff: truncated ? raw.slice(0, MAX_DIFF_CHARS) : raw,
82
+ truncated,
83
+ });
84
+ }
85
+ return commits;
86
+ }
87
+
88
+ /** Returns version, changelog sections, spec.md git diffs, and handover history for a requirement. */
89
+ export function apiHistory(repoArg: string, feature: string): RequirementHistory {
90
+ const { repo, featureDir } = locate(repoArg, feature);
91
+ const featureAbs = path.join(repo, featureDir);
92
+ const specFile = path.join(featureAbs, "spec.md");
93
+ const changesFile = path.join(featureAbs, "changes.md");
94
+
95
+ const specVersion = fs.existsSync(specFile) ? parseSpecVersion(fs.readFileSync(specFile, "utf8")) : null;
96
+ const changes = fs.existsSync(changesFile) ? parseChanges(fs.readFileSync(changesFile, "utf8")) : [];
97
+ const posixSpec = `${featureDir.split(path.sep).join("/")}/spec.md`;
98
+ const commits = readGitHistory(repo, posixSpec);
99
+ const owner = readOwner(featureAbs);
100
+
101
+ return { specVersion, changes, commits, owner };
102
+ }