codet-pi-project-map 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +172 -2
- package/extensions/index.ts +2 -0
- package/extensions/project-map.ts +430 -0
- package/package.json +54 -4
- package/skills/project-context/SKILL.md +52 -0
- package/skills/project-scan/SKILL.md +122 -0
- package/skills/project-scan/references/metadata-protocol.md +159 -0
- package/src/actions.ts +280 -0
- package/src/cache.ts +63 -0
- package/src/ignore.ts +142 -0
- package/src/parse.ts +304 -0
- package/src/project.ts +247 -0
- package/src/render.ts +296 -0
- package/src/scan.ts +167 -0
- package/src/types.ts +102 -0
- package/src/write.ts +190 -0
- package/templates/AGENTS-project-map-rules.md +9 -0
- package/templates/project-mapignore.template +17 -0
- package/templates/purpose.template +12 -0
package/src/ignore.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 扫描边界:内置默认忽略 + .gitignore + .project-mapignore。
|
|
3
|
+
*
|
|
4
|
+
* 只实现 gitignore 里最常用的子集:注释、取反 `!`、目录后缀 `/`、`*`、`**`、`?`。
|
|
5
|
+
* 不追求与 git 完全等价——边界由 .project-mapignore 显式控制,规则简单可预期更重要。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
|
|
11
|
+
import type { IgnoreRule } from "./types.ts";
|
|
12
|
+
|
|
13
|
+
/** 无论 ignore 文件怎么写都跳过(生成物 / 依赖 / 缓存目录) */
|
|
14
|
+
const BUILTIN_PATTERNS: readonly string[] = [
|
|
15
|
+
"node_modules/",
|
|
16
|
+
".git/",
|
|
17
|
+
".hg/",
|
|
18
|
+
".svn/",
|
|
19
|
+
"dist/",
|
|
20
|
+
"build/",
|
|
21
|
+
"out/",
|
|
22
|
+
"target/",
|
|
23
|
+
"coverage/",
|
|
24
|
+
"vendor/",
|
|
25
|
+
"generated/",
|
|
26
|
+
"gen/",
|
|
27
|
+
".cache/",
|
|
28
|
+
".next/",
|
|
29
|
+
".nuxt/",
|
|
30
|
+
".turbo/",
|
|
31
|
+
".venv/",
|
|
32
|
+
"venv/",
|
|
33
|
+
"__pycache__/",
|
|
34
|
+
".mypy_cache/",
|
|
35
|
+
".pytest_cache/",
|
|
36
|
+
".gradle/",
|
|
37
|
+
".mvn/",
|
|
38
|
+
".idea/",
|
|
39
|
+
".vscode/",
|
|
40
|
+
"obj/",
|
|
41
|
+
"Pods/",
|
|
42
|
+
"DerivedData/",
|
|
43
|
+
// 本插件自己的派生产物
|
|
44
|
+
".pi/project-map/",
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
function translate(pattern: string): string {
|
|
48
|
+
let out = "";
|
|
49
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
50
|
+
const ch = pattern[i];
|
|
51
|
+
if (ch === "*") {
|
|
52
|
+
if (pattern[i + 1] === "*") {
|
|
53
|
+
i++;
|
|
54
|
+
if (pattern[i + 1] === "/") {
|
|
55
|
+
i++;
|
|
56
|
+
out += "(?:.*/)?";
|
|
57
|
+
} else {
|
|
58
|
+
out += ".*";
|
|
59
|
+
}
|
|
60
|
+
} else {
|
|
61
|
+
out += "[^/]*";
|
|
62
|
+
}
|
|
63
|
+
} else if (ch === "?") {
|
|
64
|
+
out += "[^/]";
|
|
65
|
+
} else if ("\\^$.|+()[]{}".includes(ch)) {
|
|
66
|
+
out += `\\${ch}`;
|
|
67
|
+
} else {
|
|
68
|
+
out += ch;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 把一行 gitignore 风格规则编译成正则;注释/空行返回 null */
|
|
75
|
+
export function compilePattern(pattern: string, source = "project-mapignore"): IgnoreRule | null {
|
|
76
|
+
let p = pattern.trim();
|
|
77
|
+
if (!p || p.startsWith("#")) return null;
|
|
78
|
+
|
|
79
|
+
const negate = p.startsWith("!");
|
|
80
|
+
if (negate) p = p.slice(1).trim();
|
|
81
|
+
p = p.replace(/^\.\//, "");
|
|
82
|
+
|
|
83
|
+
const dirOnly = p.endsWith("/");
|
|
84
|
+
if (dirOnly) p = p.replace(/\/+$/, "");
|
|
85
|
+
|
|
86
|
+
const anchored = p.startsWith("/");
|
|
87
|
+
if (anchored) p = p.slice(1);
|
|
88
|
+
if (!p) return null;
|
|
89
|
+
|
|
90
|
+
const body = translate(p);
|
|
91
|
+
let regex: RegExp;
|
|
92
|
+
if (anchored) regex = new RegExp(`^${body}(?:/.*)?$`);
|
|
93
|
+
else if (p.includes("/")) regex = new RegExp(`^(?:.*/)?${body}(?:/.*)?$`);
|
|
94
|
+
else regex = new RegExp(`(?:^|/)${body}(?:/.*)?$`);
|
|
95
|
+
|
|
96
|
+
return { regex, negate, dirOnly, source };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function readPatterns(cwd: string, file: string): IgnoreRule[] {
|
|
100
|
+
const path = join(cwd, file);
|
|
101
|
+
if (!existsSync(path)) return [];
|
|
102
|
+
let text: string;
|
|
103
|
+
try {
|
|
104
|
+
text = readFileSync(path, "utf-8");
|
|
105
|
+
} catch {
|
|
106
|
+
return [];
|
|
107
|
+
}
|
|
108
|
+
return text
|
|
109
|
+
.split(/\r?\n/)
|
|
110
|
+
.map((line) => compilePattern(line, file))
|
|
111
|
+
.filter((r): r is IgnoreRule => r !== null);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 加载边界:内置 → .gitignore → .project-mapignore(后者可覆盖前者) */
|
|
115
|
+
export function loadIgnoreRules(cwd: string): IgnoreRule[] {
|
|
116
|
+
const builtin = BUILTIN_PATTERNS.map((p) => compilePattern(p, "builtin")).filter(
|
|
117
|
+
(r): r is IgnoreRule => r !== null,
|
|
118
|
+
);
|
|
119
|
+
return [...builtin, ...readPatterns(cwd, ".gitignore"), ...readPatterns(cwd, ".project-mapignore")];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 判断相对路径是否被忽略。
|
|
124
|
+
* 依次用每条规则匹配"路径本身 + 各级祖先目录",后命中的规则覆盖先命中的。
|
|
125
|
+
*/
|
|
126
|
+
export function isIgnored(relPath: string, isDir: boolean, rules: readonly IgnoreRule[]): boolean {
|
|
127
|
+
const parts = relPath.split("/");
|
|
128
|
+
let ignored = false;
|
|
129
|
+
for (const rule of rules) {
|
|
130
|
+
let hit = false;
|
|
131
|
+
// 祖先目录本身是目录,dirOnly 规则也应参与匹配
|
|
132
|
+
for (let i = 1; i < parts.length; i++) {
|
|
133
|
+
if (rule.regex.test(parts.slice(0, i).join("/"))) {
|
|
134
|
+
hit = true;
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (!hit && (!rule.dirOnly || isDir) && rule.regex.test(relPath)) hit = true;
|
|
139
|
+
if (hit) ignored = !rule.negate;
|
|
140
|
+
}
|
|
141
|
+
return ignored;
|
|
142
|
+
}
|
package/src/parse.ts
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Metadata 协议解析器(Business / Constraints 与 .purpose)。
|
|
3
|
+
*
|
|
4
|
+
* 协议只依赖普通行注释,不改变语言语义:
|
|
5
|
+
* Business: <一句话业务职责>
|
|
6
|
+
* Constraints:
|
|
7
|
+
* - <不可违反的约束>
|
|
8
|
+
*
|
|
9
|
+
* 解析范围限文件头 60 行:metadata 属于"文件说明",不是代码注释里的普通文字。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { DirPurpose, ParsedFile } from "./types.ts";
|
|
13
|
+
|
|
14
|
+
interface LanguageInfo {
|
|
15
|
+
prefix: string;
|
|
16
|
+
language: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 支持 metadata 的源码后缀 → 注释前缀 */
|
|
20
|
+
const EXTENSIONS: Record<string, LanguageInfo> = {
|
|
21
|
+
".ts": { prefix: "//", language: "typescript" },
|
|
22
|
+
".tsx": { prefix: "//", language: "typescript" },
|
|
23
|
+
".mts": { prefix: "//", language: "typescript" },
|
|
24
|
+
".cts": { prefix: "//", language: "typescript" },
|
|
25
|
+
".js": { prefix: "//", language: "javascript" },
|
|
26
|
+
".jsx": { prefix: "//", language: "javascript" },
|
|
27
|
+
".mjs": { prefix: "//", language: "javascript" },
|
|
28
|
+
".cjs": { prefix: "//", language: "javascript" },
|
|
29
|
+
".java": { prefix: "//", language: "java" },
|
|
30
|
+
".kt": { prefix: "//", language: "kotlin" },
|
|
31
|
+
".kts": { prefix: "//", language: "kotlin" },
|
|
32
|
+
".scala": { prefix: "//", language: "scala" },
|
|
33
|
+
".groovy": { prefix: "//", language: "groovy" },
|
|
34
|
+
".cs": { prefix: "//", language: "csharp" },
|
|
35
|
+
".go": { prefix: "//", language: "go" },
|
|
36
|
+
".swift": { prefix: "//", language: "swift" },
|
|
37
|
+
".dart": { prefix: "//", language: "dart" },
|
|
38
|
+
".c": { prefix: "//", language: "c" },
|
|
39
|
+
".h": { prefix: "//", language: "c" },
|
|
40
|
+
".cc": { prefix: "//", language: "cpp" },
|
|
41
|
+
".cpp": { prefix: "//", language: "cpp" },
|
|
42
|
+
".hpp": { prefix: "//", language: "cpp" },
|
|
43
|
+
".m": { prefix: "//", language: "objective-c" },
|
|
44
|
+
".mm": { prefix: "//", language: "objective-c" },
|
|
45
|
+
".php": { prefix: "//", language: "php" },
|
|
46
|
+
".rs": { prefix: "//", language: "rust" },
|
|
47
|
+
".py": { prefix: "#", language: "python" },
|
|
48
|
+
".rb": { prefix: "#", language: "ruby" },
|
|
49
|
+
".sh": { prefix: "#", language: "shell" },
|
|
50
|
+
".bash": { prefix: "#", language: "shell" },
|
|
51
|
+
".zsh": { prefix: "#", language: "shell" },
|
|
52
|
+
".fish": { prefix: "#", language: "shell" },
|
|
53
|
+
".pl": { prefix: "#", language: "perl" },
|
|
54
|
+
".pm": { prefix: "#", language: "perl" },
|
|
55
|
+
".r": { prefix: "#", language: "r" },
|
|
56
|
+
".yml": { prefix: "#", language: "yaml" },
|
|
57
|
+
".yaml": { prefix: "#", language: "yaml" },
|
|
58
|
+
".toml": { prefix: "#", language: "toml" },
|
|
59
|
+
".conf": { prefix: "#", language: "config" },
|
|
60
|
+
".tf": { prefix: "#", language: "hcl" },
|
|
61
|
+
".nix": { prefix: "#", language: "nix" },
|
|
62
|
+
".ex": { prefix: "#", language: "elixir" },
|
|
63
|
+
".exs": { prefix: "#", language: "elixir" },
|
|
64
|
+
".lua": { prefix: "--", language: "lua" },
|
|
65
|
+
".sql": { prefix: "--", language: "sql" },
|
|
66
|
+
".hs": { prefix: "--", language: "haskell" },
|
|
67
|
+
".elm": { prefix: "--", language: "elm" },
|
|
68
|
+
".clj": { prefix: ";", language: "clojure" },
|
|
69
|
+
".cljs": { prefix: ";", language: "clojure" },
|
|
70
|
+
".el": { prefix: ";", language: "elisp" },
|
|
71
|
+
".vim": { prefix: '"', language: "vim" },
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const TEST_PATH_RE =
|
|
75
|
+
/(^|\/)(__tests__|test|tests|spec|specs|testdata|fixtures|mocks|snapshots|e2e)\//i;
|
|
76
|
+
const TEST_FILE_RE =
|
|
77
|
+
/(\.(test|spec|e2e)\.[^/]+$)|(^test_.*\.py$)|(_test\.(go|py|rb|rs)$)|(^\d+_.*\.(py|rb)$)/i;
|
|
78
|
+
const GENERATED_PATH_RE =
|
|
79
|
+
/(^|\/)(generated|__generated__|auto-generated|dist|build|out|coverage|vendor|node_modules)\//i;
|
|
80
|
+
const GENERATED_HEADER_RE = /(Code generated .*DO NOT EDIT|@generated|This file was generated)/i;
|
|
81
|
+
/** 声明文件 / 压缩产物 / *.gen.* 视为可选(通常由工具生成) */
|
|
82
|
+
const OPTIONAL_FILE_RE = /\.(d\.ts|d\.mts|min\.js|gen\.[cm]?[jt]sx?)$/i;
|
|
83
|
+
|
|
84
|
+
/** 默认要求 metadata 的生产源码根目录 */
|
|
85
|
+
const REQUIRED_ROOTS: readonly RegExp[] = [
|
|
86
|
+
/^src\//,
|
|
87
|
+
/^app\//,
|
|
88
|
+
/^server\//,
|
|
89
|
+
/^service\//,
|
|
90
|
+
/^services\//,
|
|
91
|
+
/^domain\//,
|
|
92
|
+
/^lib\//,
|
|
93
|
+
/^internal\//,
|
|
94
|
+
/^cmd\//,
|
|
95
|
+
/^api\//,
|
|
96
|
+
/^extensions\//,
|
|
97
|
+
/^plugins\//,
|
|
98
|
+
/^(packages|apps|modules)\/[^/]+\/src\//,
|
|
99
|
+
];
|
|
100
|
+
|
|
101
|
+
export function languageOf(file: string): LanguageInfo | undefined {
|
|
102
|
+
const lower = file.toLowerCase();
|
|
103
|
+
for (const [ext, info] of Object.entries(EXTENSIONS)) {
|
|
104
|
+
if (lower.endsWith(ext)) return info;
|
|
105
|
+
}
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function isSourceFile(file: string): boolean {
|
|
110
|
+
return languageOf(file) !== undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function isTestPath(file: string): boolean {
|
|
114
|
+
return TEST_PATH_RE.test(file) || TEST_FILE_RE.test(file);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function isGeneratedPath(file: string): boolean {
|
|
118
|
+
return GENERATED_PATH_RE.test(file);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 生产源码 = 必须带 Business(不在测试/生成物目录下) */
|
|
122
|
+
export function isProductionPath(file: string): boolean {
|
|
123
|
+
if (OPTIONAL_FILE_RE.test(file)) return false;
|
|
124
|
+
if (isTestPath(file) || isGeneratedPath(file)) return false;
|
|
125
|
+
return REQUIRED_ROOTS.some((re) => re.test(file));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function hasGeneratedHeader(content: string): boolean {
|
|
129
|
+
return GENERATED_HEADER_RE.test(content.split(/\r?\n/, 10).join("\n"));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 去掉行注释包装,返回注释正文;不是注释行返回 null */
|
|
133
|
+
export function stripComment(line: string, prefix: string): string | null {
|
|
134
|
+
const trimmed = line.trimStart();
|
|
135
|
+
if (!trimmed.startsWith(prefix)) return null;
|
|
136
|
+
let rest = trimmed.slice(prefix.length);
|
|
137
|
+
if (prefix === "//" && (rest.startsWith("/") || rest.startsWith("!"))) {
|
|
138
|
+
rest = rest.slice(1); // /// 或 //! 文档注释
|
|
139
|
+
} else if (prefix === "#" && rest.startsWith("!")) {
|
|
140
|
+
rest = rest.slice(1);
|
|
141
|
+
} else if (prefix === "--" && rest.startsWith("|")) {
|
|
142
|
+
rest = rest.slice(1);
|
|
143
|
+
}
|
|
144
|
+
return rest.trim();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const BUSINESS_RE = /^Business\s*[::]\s*(.*)$/i;
|
|
148
|
+
const CONSTRAINTS_RE = /^Constraints\s*[::]\s*$/i;
|
|
149
|
+
const ITEM_RE = /^[-*+]\s+(.+)$/;
|
|
150
|
+
|
|
151
|
+
/** 解析文件头 metadata;格式问题进 problems,位置等建议进 warnings */
|
|
152
|
+
export function parseMetadata(file: string, content: string): ParsedFile {
|
|
153
|
+
const info = languageOf(file);
|
|
154
|
+
if (!info) {
|
|
155
|
+
return { file, language: "unknown", prefix: "", problems: [], warnings: [] };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const problems: string[] = [];
|
|
159
|
+
const warnings: string[] = [];
|
|
160
|
+
const lines = content.split(/\r?\n/);
|
|
161
|
+
const limit = Math.min(lines.length, 60);
|
|
162
|
+
|
|
163
|
+
let business: string | undefined;
|
|
164
|
+
let businessLine = -1;
|
|
165
|
+
let constraintsLine = -1;
|
|
166
|
+
let lastMetaLine = -1;
|
|
167
|
+
let declaredConstraints = false;
|
|
168
|
+
let inConstraints = false;
|
|
169
|
+
const constraints: string[] = [];
|
|
170
|
+
|
|
171
|
+
for (let i = 0; i < limit; i++) {
|
|
172
|
+
const body = stripComment(lines[i], info.prefix);
|
|
173
|
+
if (body === null) {
|
|
174
|
+
inConstraints = false;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const biz = BUSINESS_RE.exec(body);
|
|
179
|
+
if (biz) {
|
|
180
|
+
if (business !== undefined) {
|
|
181
|
+
problems.push(`第 ${i + 1} 行出现重复 Business(首次在第 ${businessLine} 行)`);
|
|
182
|
+
} else {
|
|
183
|
+
business = biz[1].trim();
|
|
184
|
+
businessLine = i + 1;
|
|
185
|
+
}
|
|
186
|
+
lastMetaLine = Math.max(lastMetaLine, i + 1);
|
|
187
|
+
inConstraints = false;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (CONSTRAINTS_RE.test(body)) {
|
|
192
|
+
if (declaredConstraints) problems.push(`第 ${i + 1} 行出现重复 Constraints 块`);
|
|
193
|
+
declaredConstraints = true;
|
|
194
|
+
constraintsLine = i + 1;
|
|
195
|
+
lastMetaLine = Math.max(lastMetaLine, i + 1);
|
|
196
|
+
inConstraints = true;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (inConstraints) {
|
|
201
|
+
const item = ITEM_RE.exec(body);
|
|
202
|
+
if (item) {
|
|
203
|
+
constraints.push(item[1].trim());
|
|
204
|
+
lastMetaLine = Math.max(lastMetaLine, i + 1);
|
|
205
|
+
} else if (body !== "") {
|
|
206
|
+
inConstraints = false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (businessLine > 0 && constraintsLine > 0 && constraintsLine < businessLine) {
|
|
212
|
+
problems.push(`Constraints 块(第 ${constraintsLine} 行)必须写在 Business 之后`);
|
|
213
|
+
}
|
|
214
|
+
if (declaredConstraints && constraints.length === 0) {
|
|
215
|
+
problems.push("Constraints 块为空,至少写一条约束,或整块省略");
|
|
216
|
+
}
|
|
217
|
+
if (business !== undefined && business.length === 0) {
|
|
218
|
+
problems.push("Business 内容为空");
|
|
219
|
+
}
|
|
220
|
+
if (business === undefined && declaredConstraints) {
|
|
221
|
+
problems.push("存在 Constraints 却缺少 Business");
|
|
222
|
+
}
|
|
223
|
+
if (businessLine > 20) {
|
|
224
|
+
warnings.push(`Business 位于第 ${businessLine} 行,建议放在文件头(前 20 行内)`);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const startLine = businessLine > 0 ? Math.min(businessLine, constraintsLine > 0 ? constraintsLine : businessLine) : -1;
|
|
228
|
+
const metadata =
|
|
229
|
+
business !== undefined && business.length > 0
|
|
230
|
+
? {
|
|
231
|
+
file,
|
|
232
|
+
business,
|
|
233
|
+
constraints,
|
|
234
|
+
startLine,
|
|
235
|
+
endLine: Math.max(lastMetaLine, startLine),
|
|
236
|
+
prefix: info.prefix,
|
|
237
|
+
}
|
|
238
|
+
: undefined;
|
|
239
|
+
|
|
240
|
+
return { file, language: info.language, prefix: info.prefix, metadata, problems, warnings };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const GENERIC_BUSINESS = [
|
|
244
|
+
/^(业务逻辑|业务处理|核心业务|工具类|工具函数|工具方法|常量|配置|用户服务|订单服务|数据处理|处理数据|提供.*常量|各种.*工具|通用.*工具)/,
|
|
245
|
+
/^(utility|utils?|helpers?|constants?|config|types?|services?|data)( stuff| only)?$/i,
|
|
246
|
+
];
|
|
247
|
+
|
|
248
|
+
/** 低质量元数据检查(只警告;CI 不因此失败) */
|
|
249
|
+
export function checkMetadataQuality(file: string, business: string, constraints: readonly string[]): string[] {
|
|
250
|
+
const warnings: string[] = [];
|
|
251
|
+
const base = file.split("/").pop() ?? file;
|
|
252
|
+
if (business.length > 80) warnings.push(`Business 超过 80 字(${business.length})`);
|
|
253
|
+
if (business.length < 6) warnings.push(`Business 过短(${business.length} 字),无法表达职责`);
|
|
254
|
+
if (GENERIC_BUSINESS.some((re) => re.test(business))) {
|
|
255
|
+
warnings.push("Business 过于笼统,应写清业务实体 + 操作/职责");
|
|
256
|
+
}
|
|
257
|
+
if (business.includes(base) || business.includes(base.replace(/\.[^.]+$/, ""))) {
|
|
258
|
+
warnings.push("Business 疑似仅复述文件名,应描述业务职责");
|
|
259
|
+
}
|
|
260
|
+
if (constraints.length > 12) warnings.push(`Constraints 过多(${constraints.length} 条),建议只保留真正不可破坏的约束`);
|
|
261
|
+
for (const [i, c] of constraints.entries()) {
|
|
262
|
+
if (c.length > 60) warnings.push(`第 ${i + 1} 条 Constraint 超过 60 字(${c.length})`);
|
|
263
|
+
}
|
|
264
|
+
return warnings;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** 解析 .purpose(`# .purpose` 风格的注释文件) */
|
|
268
|
+
export function parsePurpose(dir: string, content: string): DirPurpose {
|
|
269
|
+
const problems: string[] = [];
|
|
270
|
+
let business: string | undefined;
|
|
271
|
+
const contains: string[] = [];
|
|
272
|
+
const rules: string[] = [];
|
|
273
|
+
let section: "contains" | "rules" | undefined;
|
|
274
|
+
|
|
275
|
+
for (const raw of content.split(/\r?\n/)) {
|
|
276
|
+
const line = raw.trim().replace(/^#\s?/, "").trim();
|
|
277
|
+
if (!line) continue;
|
|
278
|
+
if (line === ".purpose") continue;
|
|
279
|
+
|
|
280
|
+
const biz = BUSINESS_RE.exec(line);
|
|
281
|
+
if (biz) {
|
|
282
|
+
if (business !== undefined) problems.push("出现重复 Business");
|
|
283
|
+
else business = biz[1].trim();
|
|
284
|
+
section = undefined;
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
if (/^Contains\s*[::]\s*$/i.test(line)) {
|
|
288
|
+
section = "contains";
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
if (/^Rules\s*[::]\s*$/i.test(line)) {
|
|
292
|
+
section = "rules";
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
const item = ITEM_RE.exec(line);
|
|
296
|
+
if (!item) continue;
|
|
297
|
+
if (section === "contains") contains.push(item[1].trim());
|
|
298
|
+
else if (section === "rules") rules.push(item[1].trim());
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (!business) problems.push("缺少 Business");
|
|
302
|
+
if (business !== undefined && business.length === 0) problems.push("Business 内容为空");
|
|
303
|
+
return { dir, business, contains, rules, problems };
|
|
304
|
+
}
|
package/src/project.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 项目索引:走目录树、应用扫描边界、读源码头部 metadata、汇总目录 .purpose。
|
|
3
|
+
* 只读;不修改任何项目文件。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { execFileSync } from "node:child_process";
|
|
8
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
|
|
11
|
+
import { isIgnored, loadIgnoreRules } from "./ignore.ts";
|
|
12
|
+
import {
|
|
13
|
+
hasGeneratedHeader,
|
|
14
|
+
isProductionPath,
|
|
15
|
+
isSourceFile,
|
|
16
|
+
isTestPath,
|
|
17
|
+
parseMetadata,
|
|
18
|
+
parsePurpose,
|
|
19
|
+
} from "./parse.ts";
|
|
20
|
+
import type { DirPurpose, FileMetadata, IgnoreRule, ParsedFile } from "./types.ts";
|
|
21
|
+
|
|
22
|
+
/** 单个文件读取上限:超大文件不参与索引(多半是数据/生成物) */
|
|
23
|
+
const MAX_FILE_BYTES = 512 * 1024;
|
|
24
|
+
const MAX_FILES = 100_000;
|
|
25
|
+
|
|
26
|
+
export interface IndexedFile {
|
|
27
|
+
file: string;
|
|
28
|
+
language: string;
|
|
29
|
+
required: boolean;
|
|
30
|
+
test: boolean;
|
|
31
|
+
metadata?: FileMetadata;
|
|
32
|
+
problems: string[];
|
|
33
|
+
warnings: string[];
|
|
34
|
+
hash: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface DirInfo {
|
|
38
|
+
dir: string;
|
|
39
|
+
purpose?: DirPurpose;
|
|
40
|
+
/** 递归包含的源文件数 */
|
|
41
|
+
fileCount: number;
|
|
42
|
+
productionCount: number;
|
|
43
|
+
directFiles: string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface ProjectIndex {
|
|
47
|
+
root: string;
|
|
48
|
+
project: string;
|
|
49
|
+
generatedAt: string;
|
|
50
|
+
scope: string;
|
|
51
|
+
changedOnly: boolean;
|
|
52
|
+
files: IndexedFile[];
|
|
53
|
+
dirs: Map<string, DirInfo>;
|
|
54
|
+
rules: readonly IgnoreRule[];
|
|
55
|
+
gitAvailable: boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface WalkOutput {
|
|
59
|
+
files: string[];
|
|
60
|
+
dirs: string[];
|
|
61
|
+
purposeFiles: string[];
|
|
62
|
+
truncated: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function walk(root: string, rules: readonly IgnoreRule[]): WalkOutput {
|
|
66
|
+
const out: WalkOutput = { files: [], dirs: [], purposeFiles: [], truncated: false };
|
|
67
|
+
|
|
68
|
+
const visit = (rel: string): void => {
|
|
69
|
+
if (out.truncated) return;
|
|
70
|
+
const abs = rel ? join(root, rel) : root;
|
|
71
|
+
let entries;
|
|
72
|
+
try {
|
|
73
|
+
entries = readdirSync(abs, { withFileTypes: true });
|
|
74
|
+
} catch {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
78
|
+
for (const entry of entries) {
|
|
79
|
+
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
80
|
+
if (entry.isSymbolicLink()) continue;
|
|
81
|
+
if (entry.isDirectory()) {
|
|
82
|
+
if (isIgnored(childRel, true, rules)) continue;
|
|
83
|
+
out.dirs.push(childRel);
|
|
84
|
+
visit(childRel);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (!entry.isFile()) continue;
|
|
88
|
+
if (entry.name === ".purpose") {
|
|
89
|
+
out.purposeFiles.push(childRel);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (isIgnored(childRel, false, rules)) continue;
|
|
93
|
+
if (!isSourceFile(childRel)) continue;
|
|
94
|
+
try {
|
|
95
|
+
if (statSync(join(root, childRel)).size > MAX_FILE_BYTES) continue;
|
|
96
|
+
} catch {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
out.files.push(childRel);
|
|
100
|
+
if (out.files.length >= MAX_FILES) {
|
|
101
|
+
out.truncated = true;
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
visit("");
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** git 工作区改动文件(相对 posix 路径);非 git 仓库返回空 */
|
|
112
|
+
export function changedFiles(root: string): { files: string[]; available: boolean } {
|
|
113
|
+
const run = (args: string[]): string[] => {
|
|
114
|
+
try {
|
|
115
|
+
return execFileSync("git", args, {
|
|
116
|
+
cwd: root,
|
|
117
|
+
encoding: "utf-8",
|
|
118
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
119
|
+
}).split("\n");
|
|
120
|
+
} catch {
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const probe = run(["rev-parse", "--is-inside-work-tree"]).join("").trim();
|
|
126
|
+
if (probe !== "true") return { files: [], available: false };
|
|
127
|
+
|
|
128
|
+
const files = new Set<string>();
|
|
129
|
+
for (const line of run(["diff", "--name-only", "HEAD"])) {
|
|
130
|
+
const p = line.trim();
|
|
131
|
+
if (p) files.add(p);
|
|
132
|
+
}
|
|
133
|
+
for (const line of run(["status", "--porcelain"])) {
|
|
134
|
+
const p = line.slice(3).trim();
|
|
135
|
+
if (!p) continue;
|
|
136
|
+
const target = p.includes(" -> ") ? p.split(" -> ").pop() ?? p : p;
|
|
137
|
+
files.add(target);
|
|
138
|
+
}
|
|
139
|
+
return { files: [...files], available: true };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function readText(abs: string): string | undefined {
|
|
143
|
+
try {
|
|
144
|
+
return readFileSync(abs, "utf-8");
|
|
145
|
+
} catch {
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface IndexOptions {
|
|
151
|
+
cwd: string;
|
|
152
|
+
dir?: string;
|
|
153
|
+
changed?: boolean;
|
|
154
|
+
rules?: readonly IgnoreRule[];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function buildIndex(opts: IndexOptions): ProjectIndex {
|
|
158
|
+
const root = opts.cwd;
|
|
159
|
+
const rules = opts.rules ?? loadIgnoreRules(root);
|
|
160
|
+
const scope = opts.dir ? opts.dir.replace(/^\.\//, "").replace(/\/+$/, "") : "";
|
|
161
|
+
const scopeAbs = scope ? join(root, scope) : root;
|
|
162
|
+
if (scope && !existsSync(scopeAbs)) {
|
|
163
|
+
throw new Error(`扫描目录不存在: ${scope}`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const walked = walk(scopeAbs, rules);
|
|
167
|
+
const prefix = scope ? `${scope}/` : "";
|
|
168
|
+
let selected = walked.files.map((f) => prefix + f);
|
|
169
|
+
|
|
170
|
+
let changedOnly = false;
|
|
171
|
+
let gitAvailable = true;
|
|
172
|
+
if (opts.changed) {
|
|
173
|
+
const changed = changedFiles(root);
|
|
174
|
+
gitAvailable = changed.available;
|
|
175
|
+
changedOnly = true;
|
|
176
|
+
const set = new Set(changed.files.map((f) => f.replace(/^\.\//, "")));
|
|
177
|
+
selected = selected.filter((f) => set.has(f));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const files: IndexedFile[] = [];
|
|
181
|
+
for (const file of selected) {
|
|
182
|
+
const content = readText(join(root, file));
|
|
183
|
+
if (content === undefined) continue;
|
|
184
|
+
if (hasGeneratedHeader(content)) continue;
|
|
185
|
+
const parsed: ParsedFile = parseMetadata(file, content);
|
|
186
|
+
files.push({
|
|
187
|
+
file,
|
|
188
|
+
language: parsed.language,
|
|
189
|
+
required: isProductionPath(file),
|
|
190
|
+
test: isTestPath(file),
|
|
191
|
+
metadata: parsed.metadata,
|
|
192
|
+
problems: parsed.problems,
|
|
193
|
+
warnings: parsed.warnings,
|
|
194
|
+
hash: createHash("sha256").update(content).digest("hex").slice(0, 16),
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// 目录条目:先登记 scope 下全部目录,再按文件回填计数
|
|
199
|
+
const dirs = new Map<string, DirInfo>();
|
|
200
|
+
const ensureDir = (dir: string): DirInfo => {
|
|
201
|
+
let info = dirs.get(dir);
|
|
202
|
+
if (!info) {
|
|
203
|
+
info = { dir, fileCount: 0, productionCount: 0, directFiles: [] };
|
|
204
|
+
dirs.set(dir, info);
|
|
205
|
+
}
|
|
206
|
+
return info;
|
|
207
|
+
};
|
|
208
|
+
if (scope) ensureDir(scope);
|
|
209
|
+
for (const d of walked.dirs) ensureDir(prefix + d);
|
|
210
|
+
|
|
211
|
+
for (const file of files) {
|
|
212
|
+
const parts = file.file.split("/");
|
|
213
|
+
const dir = parts.slice(0, -1).join("/");
|
|
214
|
+
ensureDir(dir).directFiles.push(file.file);
|
|
215
|
+
for (let i = 1; i <= parts.length - 1; i++) {
|
|
216
|
+
const info = ensureDir(parts.slice(0, i).join("/"));
|
|
217
|
+
info.fileCount++;
|
|
218
|
+
if (file.required) info.productionCount++;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
for (const purposeFile of walked.purposeFiles) {
|
|
223
|
+
const rel = prefix + purposeFile;
|
|
224
|
+
const dir = rel.slice(0, -"/.purpose".length) || ".";
|
|
225
|
+
const content = readText(join(root, rel));
|
|
226
|
+
if (content === undefined) continue;
|
|
227
|
+
ensureDir(dir).purpose = parsePurpose(dir, content);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return {
|
|
231
|
+
root,
|
|
232
|
+
project: root.split(/[\\/]/).filter(Boolean).pop() ?? "project",
|
|
233
|
+
generatedAt: new Date().toISOString(),
|
|
234
|
+
scope: scope || ".",
|
|
235
|
+
changedOnly,
|
|
236
|
+
files,
|
|
237
|
+
dirs,
|
|
238
|
+
rules,
|
|
239
|
+
gitAvailable,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** 相对 root 的目录深度(scope 为 1) */
|
|
244
|
+
export function dirDepth(dir: string): number {
|
|
245
|
+
if (!dir || dir === ".") return 0;
|
|
246
|
+
return dir.split("/").length;
|
|
247
|
+
}
|