forked from Ikalus1988/MisakaNet
-
Notifications
You must be signed in to change notification settings - Fork 0
243 lines (203 loc) · 10 KB
/
Copy pathpr-shape-guard.yml
File metadata and controls
243 lines (203 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
name: PR Shape Guard
on:
pull_request_target:
types: [opened, synchronize, reopened]
permissions:
contents: read
pull-requests: read
issues: write
jobs:
audit-shape:
runs-on: ubuntu-latest
steps:
- name: Area labels (by file path)
uses: actions/labeler@v7
with:
repo-token: ${{ secrets.SHELDON_PAT || secrets.GITHUB_TOKEN }}
configuration-path: .github/labeler.yml
- name: Shape guard + auto-label
uses: actions/github-script@v9
with:
github-token: ${{ secrets.SHELDON_PAT || secrets.GITHUB_TOKEN }}
script: |
const marker = '<!-- misakanet-pr-shape-guard -->';
const pr = context.payload.pull_request;
const files = await github.paginate(
github.rest.pulls.listFiles,
{
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.number,
per_page: 100,
}
);
const names = files.map(f => f.filename);
const failures = [];
// ═══════════════════════════════════════════
// SHAPE CHECKS (failures block merge)
// ═══════════════════════════════════════════
for (const f of files) {
const name = f.filename;
// Rule 1: generated temp/patch filenames
if (name.includes(' ---') || name.endsWith('---')) {
failures.push(`**文件名污染**: \`${name}\` 看起来是生成器残留文件名。`);
}
// Rule 2: destructive README rewrite
if (name === 'README.md' && f.deletions > 120) {
failures.push(`**破坏性 README 修改**: README.md 删除了 ${f.deletions} 行,疑似替换全文而非小改。`);
}
// Rule 3: source file contains pasted markdown/diff
if (/\.(py|js|ts|go)$/.test(name) && f.patch) {
const added = f.patch
.split('\n')
.filter(line => line.startsWith('+') && !line.startsWith('+++'))
.map(line => line.slice(1));
if (added.some(line =>
line.startsWith('```') ||
line.startsWith('diff --git') ||
line.startsWith('@@ ') ||
line.includes('# Change this line:')
)) {
failures.push(`**Diff/Markdown 泄露**: \`${name}\` 中疑似粘贴了 patch 或 markdown 代码块。`);
}
}
// Rule 4: large deletion in core search file
if (name === 'search_knowledge.py' && f.deletions > 100) {
failures.push(`**核心文件高风险删除**: \`search_knowledge.py\` 删除了 ${f.deletions} 行,需要人工 review。`);
}
// Rule 5: generated cache / build artifacts
const cachePatterns = [/__pycache__\//, /\.pyc$/, /\.pytest_cache\//, /\.egg-info\//];
if (cachePatterns.some(p => p.test(name))) {
failures.push(`**缓存/构建产物泄露**: \`${name}\` 是自动生成的缓存文件,提交前请清理。`);
}
}
// Rule 6: docs-only title but code changed
const titleBody = `${pr.title}\n${pr.body || ''}`.toLowerCase();
const claimsDocsOnly = titleBody.includes('docs:') || titleBody.includes('docs-only') || titleBody.includes('[docs]');
const codeChanged = files.some(f => /\.(py|js|ts|go)$/.test(f.filename));
if (claimsDocsOnly && codeChanged) {
failures.push('**范围越权**: PR 声明为 docs-only/docs,但实际修改了代码文件。');
}
// Post shape guard comment if failures
if (failures.length > 0) {
const body = `${marker}
### ⚠️ PR Shape Guard detected unsafe patch patterns
Hi @${pr.user.login}, thanks for the contribution. This PR is not ready for review because its patch shape looks unsafe.
**Detected issues:**
${failures.map(x => `- ${x}`).join('\n')}
---
**How to fix:**
Please recreate or rebase the PR from \`main\` with a clean, minimal patch:
- edit the intended file directly
- do not create files like \`README.md ---\`
- do not paste markdown diff blocks into source files
- do not replace the whole README or core source file
- keep one issue per PR
Thanks — happy to review a corrected PR.
`;
const comments = await github.paginate(
github.rest.issues.listComments,
{
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
per_page: 100,
}
);
const old = comments.find(c => c.body && c.body.includes(marker));
if (old) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: old.id,
body,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body,
});
}
}
// ═══════════════════════════════════════════
// AUTO-LABEL (scope / risk / shape / quality)
// ═══════════════════════════════════════════
const toAdd = [];
const toRemove = [];
// ── Gate 1: Scope (order matters: lessons > tests > docs) ──
const isLessons = names.every(n => n.startsWith('lessons/'));
const isTests = names.every(n => /test|spec|fixture/.test(n));
const isDocs = names.every(n => n.startsWith('docs/') || n.endsWith('.md') && !n.startsWith('lessons/'));
if (isLessons && names.length > 0) {
toAdd.push('lessons-only');
toAdd.push('needs-human-review');
} else if (isTests && names.length > 0) {
toAdd.push('tests-only');
} else if (isDocs && names.length > 0) {
toAdd.push('docs-only');
}
// ── Gate 2: Risk ──
const touchesWorkflow = names.some(n => n.startsWith('.github/workflows/'));
const touchesCore = names.some(n => ['search_knowledge.py', 'misaka-protocol.json'].includes(n));
const largeDeletion = files.some(f => f.deletions > 100);
const touchesGenerated = names.some(n =>
n.startsWith('data/') || n.startsWith('docs/data/') ||
n === 'lessons/_index.json' || n === 'lessons.json'
);
if (touchesCore || largeDeletion) toAdd.push('risk:high');
if (touchesWorkflow) toAdd.push('workflow-change');
if (touchesGenerated) toAdd.push('generated-file');
// ── Gate 3: Shape (mutual exclusion, highest priority wins) ──
const isGenerated = names.some(n => n.includes(' ---') || n.endsWith('---'));
const isDestructive = files.some(f => f.filename === 'README.md' && f.deletions > 120);
const hasShapeRisk = failures.length > 0;
// Priority: destructive-rewrite > generated-file > shape-risk > shape-safe
if (isDestructive) {
toAdd.push('destructive-rewrite');
toRemove.push('shape-safe', 'shape-risk', 'generated-file');
} else if (isGenerated) {
toAdd.push('generated-file');
toRemove.push('shape-safe', 'shape-risk', 'destructive-rewrite');
} else if (hasShapeRisk) {
toAdd.push('shape-risk');
toRemove.push('shape-safe', 'generated-file', 'destructive-rewrite');
} else {
toAdd.push('shape-safe');
toRemove.push('shape-risk', 'generated-file', 'destructive-rewrite');
}
// ── Gate 4: DCO / rebase (based on commit metadata) ──
const commits = await github.paginate(
github.rest.pulls.listCommits,
{ owner: context.repo.owner, repo: context.repo.repo, pull_number: pr.number, per_page: 100 }
);
const hasDCO = commits.every(c =>
c.commit.message.includes('Signed-off-by:')
);
if (!hasDCO) toAdd.push('needs-dco');
// ── Apply labels ──
const existing = pr.labels.map(l => l.name);
const uniqueAdd = [...new Set(toAdd)].filter(l => !existing.includes(l));
const uniqueRemove = [...new Set(toRemove)].filter(l => existing.includes(l));
if (uniqueAdd.length > 0) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
labels: uniqueAdd,
});
}
for (const label of uniqueRemove) {
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
name: label,
});
} catch (e) { /* label may not exist on this PR */ }
}
if (failures.length > 0) {
core.setFailed('PR Shape Guard failed.');
}