@kangyishuai/dsh-projects 0.1.2 → 0.2.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/lib/client.js +12 -13
- package/lib/executor.js +79 -1
- package/lib/git-push.js +114 -0
- package/lib/purge.js +97 -0
- package/lib/service.js +447 -3
- package/lib/store.js +24 -1
- package/lib/tools.js +2 -0
- package/locale/en.json +6 -6
- package/locale/zh.json +6 -6
- package/package.json +1 -1
package/lib/client.js
CHANGED
|
@@ -96,20 +96,20 @@ window.__ModuleLoader__.load({
|
|
|
96
96
|
"settings.fallback": "规则都不命中时允许模型兜底提议",
|
|
97
97
|
"settings.dangerTitle": "危险动作开关(默认全关)",
|
|
98
98
|
"settings.dangerHint": "打开任何一个开关都需要你明确同意;插件不会自行打开。",
|
|
99
|
-
"settings.danger.forcePushOwnBranch.label": "
|
|
99
|
+
"settings.danger.forcePushOwnBranch.label": "允许强推自己的 dsh/ 分支",
|
|
100
100
|
"settings.danger.forcePushOwnBranch.risk":
|
|
101
|
-
"
|
|
102
|
-
"settings.danger.pushProtectedBranch.label": "
|
|
101
|
+
"用 --force-with-lease 绑定期望 SHA;远端被他人动过、分支受保护、旧 SHA 未知时一律拒绝,并记旧 SHA 供恢复。",
|
|
102
|
+
"settings.danger.pushProtectedBranch.label": "允许直推默认/保护分支",
|
|
103
103
|
"settings.danger.pushProtectedBranch.risk":
|
|
104
|
-
"
|
|
104
|
+
"需要先在项目策略里对该仓库 per-repo 授予;推前查 protection/rulesets,服务端要求 PR 时直接拒;每次审计,检测到多人协作会额外警告。",
|
|
105
105
|
"settings.danger.autoMerge.label": "允许自动合并 PR",
|
|
106
106
|
"settings.danger.autoMerge.risk":
|
|
107
107
|
"合并不可逆(只能用 revert 回退);仍受 diff 阈值与人工批准约束",
|
|
108
108
|
"settings.danger.trashAuto.label": "允许自动归档/删除到回收站",
|
|
109
109
|
"settings.danger.trashAuto.risk": "会把内容移入 trash/;可从 manifest 恢复,但不是零成本",
|
|
110
|
-
"settings.danger.purgeAfterRetention.label": "
|
|
110
|
+
"settings.danger.purgeAfterRetention.label": "允许保留期后清理回收站",
|
|
111
111
|
"settings.danger.purgeAfterRetention.risk":
|
|
112
|
-
"
|
|
112
|
+
"只处理已在回收站且超过保留期的条目;执行前生成清理清单;默认 dry-run,真删需显式确认。",
|
|
113
113
|
"settings.danger.editProfile.label": "允许修改项目策略本身",
|
|
114
114
|
"settings.danger.editProfile.risk": "协调器可能借此放宽自己的限制;风险最高",
|
|
115
115
|
"detail.archive": "归档项目",
|
|
@@ -196,14 +196,13 @@ window.__ModuleLoader__.load({
|
|
|
196
196
|
"settings.dangerTitle": "Danger switches (all off by default)",
|
|
197
197
|
"settings.dangerHint":
|
|
198
198
|
"Every switch needs your explicit consent; the plugin never turns one on by itself.",
|
|
199
|
-
"settings.danger.forcePushOwnBranch.label":
|
|
200
|
-
"Allow pushing your own dsh/ branches (normal push, not force)",
|
|
199
|
+
"settings.danger.forcePushOwnBranch.label": "Allow force-pushing your own dsh/ branches",
|
|
201
200
|
"settings.danger.forcePushOwnBranch.risk":
|
|
202
|
-
"
|
|
201
|
+
"Uses --force-with-lease bound to the expected SHA; refuses when the remote moved, the branch is protected, or the old SHA is unknown, and records the old SHA for recovery.",
|
|
203
202
|
"settings.danger.pushProtectedBranch.label":
|
|
204
|
-
"Allow pushing to protected branches
|
|
203
|
+
"Allow pushing directly to default/protected branches",
|
|
205
204
|
"settings.danger.pushProtectedBranch.risk":
|
|
206
|
-
"
|
|
205
|
+
"Requires a per-repo grant in the project policy; checks protection/rulesets first and refuses when the server requires a PR; every push is audited and multi-collaborator repos raise a warning.",
|
|
207
206
|
"settings.danger.autoMerge.label": "auto-merge PRs",
|
|
208
207
|
"settings.danger.autoMerge.risk":
|
|
209
208
|
"merging is irreversible (revert only); still gated by diff limits and human approval",
|
|
@@ -211,9 +210,9 @@ window.__ModuleLoader__.load({
|
|
|
211
210
|
"settings.danger.trashAuto.risk":
|
|
212
211
|
"moves content into trash/; restorable from manifest, but not free",
|
|
213
212
|
"settings.danger.purgeAfterRetention.label":
|
|
214
|
-
"Allow purging the trash after retention
|
|
213
|
+
"Allow purging the trash after the retention period",
|
|
215
214
|
"settings.danger.purgeAfterRetention.risk":
|
|
216
|
-
"
|
|
215
|
+
"Only touches entries already in the trash that exceed the retention period; writes a purge manifest first; dry-run by default, real deletion needs explicit confirmation.",
|
|
217
216
|
"settings.danger.editProfile.label": "edit project policy itself",
|
|
218
217
|
"settings.danger.editProfile.risk":
|
|
219
218
|
"the coordinator could loosen its own limits; highest risk",
|
package/lib/executor.js
CHANGED
|
@@ -4,10 +4,14 @@
|
|
|
4
4
|
// 批准 ≠ 可执行。批准只是「人同意了这一次」,还要开关打开、影响面在阈值内。
|
|
5
5
|
// 三种授权来源之外一律拒绝;模型输出/外部内容/peer 消息永远不算授权。
|
|
6
6
|
|
|
7
|
+
import { planForcePush } from "./git-push.js";
|
|
8
|
+
|
|
7
9
|
/** 可执行的危险动作(与 tools.js 的 REQUESTABLE_ACTIONS 同集合,但语义不同:
|
|
8
10
|
* 这里问的是「能不能执行」,那边问的是「能不能申请」。 */
|
|
9
11
|
export const DANGER_ACTIONS = Object.freeze([
|
|
10
12
|
"push-branch",
|
|
13
|
+
"push-protected-branch",
|
|
14
|
+
"purge-trash",
|
|
11
15
|
"merge",
|
|
12
16
|
"delete-thread",
|
|
13
17
|
"delete-project",
|
|
@@ -25,6 +29,10 @@ export function switchForAction(action) {
|
|
|
25
29
|
switch (action) {
|
|
26
30
|
case "push-branch":
|
|
27
31
|
return "forcePushOwnBranch";
|
|
32
|
+
case "push-protected-branch":
|
|
33
|
+
return "pushProtectedBranch";
|
|
34
|
+
case "purge-trash":
|
|
35
|
+
return "purgeAfterRetention";
|
|
28
36
|
case "merge":
|
|
29
37
|
return "autoMerge";
|
|
30
38
|
case "delete-thread":
|
|
@@ -105,6 +113,14 @@ export function planCommand(action, args) {
|
|
|
105
113
|
const nonEmpty = (/** @type {unknown} */ value) =>
|
|
106
114
|
typeof value === "string" && value.trim() !== "";
|
|
107
115
|
|
|
116
|
+
if (action === "push-branch" && args?.force === true) {
|
|
117
|
+
// 强推:走 git-push 的 --force-with-lease(绑定期望 SHA),不接受裸 --force
|
|
118
|
+
return planForcePush({
|
|
119
|
+
branch: String(args?.branch ?? ""),
|
|
120
|
+
expectedSha: String(args?.expectedSha ?? ""),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
108
124
|
if (action === "push-branch") {
|
|
109
125
|
const branch = String(args?.branch ?? "").trim();
|
|
110
126
|
if (!nonEmpty(branch)) return { error: "branch-required" };
|
|
@@ -114,10 +130,27 @@ export function planCommand(action, args) {
|
|
|
114
130
|
return { argv: ["git", "push", "-u", "origin", branch] };
|
|
115
131
|
}
|
|
116
132
|
|
|
133
|
+
if (action === "push-protected-branch") {
|
|
134
|
+
const branch = String(args?.branch ?? "").trim();
|
|
135
|
+
if (!nonEmpty(branch)) return { error: "branch-required" };
|
|
136
|
+
// 直推保护/默认分支:不带 -u(可能不是我们的分支),也**绝不**带 --force
|
|
137
|
+
return { argv: ["git", "push", "origin", branch] };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (action === "purge-trash") {
|
|
141
|
+
// 真正的删除由 service 用 fs 做;这里只表达「这是内部动作」
|
|
142
|
+
return { argv: ["purge-trash", String(args?.confirm ?? "")] };
|
|
143
|
+
}
|
|
144
|
+
|
|
117
145
|
if (action === "merge") {
|
|
118
146
|
const prNumber = Number(args?.prNumber);
|
|
119
147
|
if (!Number.isInteger(prNumber) || prNumber <= 0) return { error: "pr-required" };
|
|
120
|
-
|
|
148
|
+
// **必须**带 --repo:否则 gh 会合并「宿主进程当前目录所在仓库」里同号的 PR。
|
|
149
|
+
// 这是 2026-11-21 真机 e2e 抓到的真缺陷:命令跑在 dsh-plugins 仓库里,
|
|
150
|
+
// 恰好那里 PR #1 已合并、gh 返回 0,于是插件误判成功,而目标 PR 根本没动。
|
|
151
|
+
const repo = String(args?.repo ?? "").trim();
|
|
152
|
+
if (!/^[\w.-]+\/[\w.-]+$/u.test(repo)) return { error: "repo-required" };
|
|
153
|
+
return { argv: ["gh", "pr", "merge", String(prNumber), "--squash", "--repo", repo] };
|
|
121
154
|
}
|
|
122
155
|
|
|
123
156
|
if (action === "delete-thread") {
|
|
@@ -165,3 +198,48 @@ export function recoveryEvidence(action, args, result) {
|
|
|
165
198
|
return { ...base, before: String(result?.before ?? ""), after: String(result?.after ?? "") };
|
|
166
199
|
return base;
|
|
167
200
|
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* 合并前的前置校验(规格 §7.5 行 3 的硬前提)。纯函数便于单测:
|
|
204
|
+
* 只从 `gh pr view --json` 的结果判断,不假设任何外部状态。
|
|
205
|
+
* @param {{ isDraft?: boolean, mergeable?: string, state?: string }|null} pr
|
|
206
|
+
* @returns {{ ok: boolean, reason?: string }}
|
|
207
|
+
*/
|
|
208
|
+
export function checkMergePreflight(pr) {
|
|
209
|
+
if (!pr || typeof pr !== "object") return { ok: false, reason: "merge/pr-unknown" };
|
|
210
|
+
if (String(pr.state ?? "OPEN").toUpperCase() !== "OPEN")
|
|
211
|
+
return { ok: false, reason: "merge/pr-not-open" };
|
|
212
|
+
// draft PR 合并会被 GitHub 拒绝;auto-merge 也不该替人「先转正再合并」
|
|
213
|
+
if (pr.isDraft === true) return { ok: false, reason: "merge/pr-is-draft" };
|
|
214
|
+
const mergeable = String(pr.mergeable ?? "UNKNOWN").toUpperCase();
|
|
215
|
+
if (mergeable === "CONFLICTING") return { ok: false, reason: "merge/pr-conflicting" };
|
|
216
|
+
if (mergeable !== "MERGEABLE") return { ok: false, reason: "merge/pr-mergeable-unknown" };
|
|
217
|
+
return { ok: true };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 从 git remote URL 里取 owner/repo(支持 https 与 ssh 两种写法)。
|
|
222
|
+
* @param {string|null} url
|
|
223
|
+
* @returns {string}
|
|
224
|
+
*/
|
|
225
|
+
export function parseRepoFromRemote(url) {
|
|
226
|
+
const text = String(url ?? "")
|
|
227
|
+
.trim()
|
|
228
|
+
.replace(/\.git$/u, "");
|
|
229
|
+
const https = text.match(/github\.com[/:]([\w.-]+)\/([\w.-]+)$/u);
|
|
230
|
+
if (https) return `${https[1]}/${https[2]}`;
|
|
231
|
+
const ssh = text.match(/^git@[\w.-]+:([\w.-]+)\/([\w.-]+)$/u);
|
|
232
|
+
if (ssh) return `${ssh[1]}/${ssh[2]}`;
|
|
233
|
+
return "";
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* 哪些前置失败值得等一会儿再试。GitHub 在 PR 刚创建后的一两秒内可能返回
|
|
238
|
+
* `mergeable: UNKNOWN`(服务端还在算),这不是「不能合并」,重试几次就会变成 MERGEABLE。
|
|
239
|
+
* 其余失败(draft / 冲突 / 已关闭)重试没有意义,直接拒绝。
|
|
240
|
+
* @param {string} reason
|
|
241
|
+
* @returns {boolean}
|
|
242
|
+
*/
|
|
243
|
+
export function shouldRetryPreflight(reason) {
|
|
244
|
+
return String(reason ?? "") === "merge/pr-mergeable-unknown";
|
|
245
|
+
}
|
package/lib/git-push.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 推送类危险动作的纯逻辑:命令形状 + 硬前提判定(规格 §7.5 行 1 / 行 2)。
|
|
3
|
+
// 不碰 I/O:gh/git 的查询结果由调用方拿到后传进来,便于单测。
|
|
4
|
+
|
|
5
|
+
/** 插件自建分支的前缀(与 worktree.js 的 BRANCH_PREFIX 保持一致)。 */
|
|
6
|
+
export const OWN_BRANCH_PREFIX = "dsh/";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 强推自己分支的命令:**必须**用 `--force-with-lease` 并绑定期望的旧 SHA。
|
|
10
|
+
* 裸 `--force` 会覆盖别人在这期间推上去的提交,规格明确不提供那种能力。
|
|
11
|
+
* @param {{ branch: string, expectedSha: string }} input
|
|
12
|
+
* @returns {{ argv: string[] } | { error: string }}
|
|
13
|
+
*/
|
|
14
|
+
export function planForcePush(input) {
|
|
15
|
+
const branch = String(input?.branch ?? "").trim();
|
|
16
|
+
const expectedSha = String(input?.expectedSha ?? "").trim();
|
|
17
|
+
if (!new RegExp(`^${OWN_BRANCH_PREFIX}[A-Za-z0-9._/-]+$`, "u").test(branch)) {
|
|
18
|
+
return { error: "force-push/branch-not-ours" };
|
|
19
|
+
}
|
|
20
|
+
if (!/^[0-9a-f]{7,40}$/u.test(expectedSha)) return { error: "force-push/sha-required" };
|
|
21
|
+
return {
|
|
22
|
+
argv: ["git", "push", `--force-with-lease=${branch}:${expectedSha}`, "origin", branch],
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 强推的硬前提(四条全部满足才放行):
|
|
28
|
+
* ① 分支由插件创建并有记录(thread.branch === branch 且带 dsh/ 前缀)
|
|
29
|
+
* ② 无他人提交 —— 用「远端 HEAD 是否还等于我们上次推上去的 SHA」判定:
|
|
30
|
+
* 不相等说明期间有别的提交(人或别的工具)上去了,强推会覆盖它
|
|
31
|
+
* ③ 非默认 / 非保护分支
|
|
32
|
+
* ④ 期望旧 SHA 已知(用于 --force-with-lease 与审计)
|
|
33
|
+
* @param {{ branch?: string|null, threadBranch?: string|null, expectedSha?: string, remoteHeadSha?: string, lastPushedSha?: string|null, protectedBranch?: boolean }} input
|
|
34
|
+
* @returns {{ ok: true } | { ok: false, reason: string }}
|
|
35
|
+
*/
|
|
36
|
+
export function checkForcePushPrereqs(input) {
|
|
37
|
+
const branch = String(input?.branch ?? "").trim();
|
|
38
|
+
const threadBranch = String(input?.threadBranch ?? "").trim();
|
|
39
|
+
if (threadBranch === "" || threadBranch !== branch) {
|
|
40
|
+
return { ok: false, reason: "force-push/branch-not-recorded" };
|
|
41
|
+
}
|
|
42
|
+
if (!branch.startsWith(OWN_BRANCH_PREFIX)) {
|
|
43
|
+
return { ok: false, reason: "force-push/branch-not-ours" };
|
|
44
|
+
}
|
|
45
|
+
if (input?.protectedBranch === true) return { ok: false, reason: "force-push/branch-protected" };
|
|
46
|
+
const expectedSha = String(input?.expectedSha ?? "").trim();
|
|
47
|
+
if (!/^[0-9a-f]{7,40}$/u.test(expectedSha)) {
|
|
48
|
+
return { ok: false, reason: "force-push/sha-required" };
|
|
49
|
+
}
|
|
50
|
+
// ② 无他人提交:远端 HEAD 必须仍是我们记录过的那个 SHA
|
|
51
|
+
const lastPushed = String(input?.lastPushedSha ?? "").trim();
|
|
52
|
+
const remoteHead = String(input?.remoteHeadSha ?? "").trim();
|
|
53
|
+
if (lastPushed !== "" && remoteHead !== "" && !remoteHead.startsWith(lastPushed.slice(0, 7))) {
|
|
54
|
+
return { ok: false, reason: "force-push/remote-moved" };
|
|
55
|
+
}
|
|
56
|
+
return { ok: true };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 直推保护/默认分支的硬前提(规格 §7.5 行 2 ①):服务端必须允许直接推。
|
|
61
|
+
* GitHub 的保护配置里 `required_pull_request_reviews` 存在 = 必须走 PR,直接推会被拒;
|
|
62
|
+
* rulesets 里针对该分支的 `pull_request` 规则同理。
|
|
63
|
+
* @param {{ protection?: any, rulesets?: any[], branch?: string }} input
|
|
64
|
+
* @returns {{ ok: true } | { ok: false, reason: string }}
|
|
65
|
+
*/
|
|
66
|
+
export function checkProtectedPushPrereqs(input) {
|
|
67
|
+
const protection = input?.protection;
|
|
68
|
+
if (protection && typeof protection === "object") {
|
|
69
|
+
if (protection.required_pull_request_reviews) {
|
|
70
|
+
return { ok: false, reason: "protected-push/requires-pull-request" };
|
|
71
|
+
}
|
|
72
|
+
if (protection.lock_branch?.enabled === true) {
|
|
73
|
+
return { ok: false, reason: "protected-push/branch-locked" };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const rulesets = Array.isArray(input?.rulesets) ? input.rulesets : [];
|
|
77
|
+
for (const ruleset of rulesets) {
|
|
78
|
+
if (ruleset?.target !== "branch") continue;
|
|
79
|
+
const conditions = ruleset?.conditions?.ref_name;
|
|
80
|
+
const includes = Array.isArray(conditions?.include) ? conditions.include : [];
|
|
81
|
+
const targetsDefault =
|
|
82
|
+
includes.includes("~DEFAULT_BRANCH") ||
|
|
83
|
+
includes.some((/** @type {string} */ pattern) => pattern === "~ALL");
|
|
84
|
+
if (!targetsDefault) continue;
|
|
85
|
+
if (ruleset?.enforcement !== "active") continue;
|
|
86
|
+
const types = (Array.isArray(ruleset?.rules) ? ruleset.rules : []).map(
|
|
87
|
+
(/** @type {any} */ rule) => String(rule?.type ?? ""),
|
|
88
|
+
);
|
|
89
|
+
if (types.includes("pull_request")) {
|
|
90
|
+
return { ok: false, reason: "protected-push/ruleset-requires-pull-request" };
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return { ok: true };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 多人协作判定:最近提交里出现多个不同作者就认为「有别人在这个仓库干活」。
|
|
98
|
+
* 规格 §7.5 行 2 ③ 要求在检测到多人协作时强警告(不禁止,但要让人看见)。
|
|
99
|
+
* @param {any[]|null} commits `gh api repos/{owner}/{repo}/commits` 的结果
|
|
100
|
+
* @returns {{ collaborators: number, multi: boolean, sample: string[] }}
|
|
101
|
+
*/
|
|
102
|
+
export function countCollaborators(commits) {
|
|
103
|
+
const list = Array.isArray(commits) ? commits : [];
|
|
104
|
+
/** @type {Set<string>} */
|
|
105
|
+
const authors = new Set();
|
|
106
|
+
for (const commit of list) {
|
|
107
|
+
const login = String(commit?.author?.login ?? "").trim();
|
|
108
|
+
const name = String(commit?.commit?.author?.name ?? "").trim();
|
|
109
|
+
const key = login !== "" ? login : name;
|
|
110
|
+
if (key !== "") authors.add(key);
|
|
111
|
+
}
|
|
112
|
+
const sample = [...authors].slice(0, 5);
|
|
113
|
+
return { collaborators: authors.size, multi: authors.size > 1, sample };
|
|
114
|
+
}
|
package/lib/purge.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 回收站保留期清理的纯逻辑(规格 §7.5 行 4c):只挑「已在回收站且超保留期」的条目,
|
|
3
|
+
// 并在删除前产出可恢复清单。零 I/O,扫描与删除由 service 做。
|
|
4
|
+
|
|
5
|
+
/** 默认保留天数(与项目 policy.budget 无关,属于删除策略)。 */
|
|
6
|
+
export const DEFAULT_RETENTION_DAYS = 30;
|
|
7
|
+
|
|
8
|
+
/** 一天毫秒。 */
|
|
9
|
+
export const DAY_MS = 24 * 60 * 60 * 1000;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 从目录名 `trash/<projectId>-<isoStamp>` 里取时间戳。
|
|
13
|
+
* 目录名由 trashDirFor() 生成(冒号与点被替换成 `-`)。
|
|
14
|
+
* @param {string} name
|
|
15
|
+
* @returns {number|null}
|
|
16
|
+
*/
|
|
17
|
+
export function deletedAtFromName(name) {
|
|
18
|
+
const match = String(name ?? "").match(/^(.+)-(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z)$/u);
|
|
19
|
+
if (!match) return null;
|
|
20
|
+
const iso = match[2].replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/u, "T$1:$2:$3.$4Z");
|
|
21
|
+
const time = Date.parse(iso);
|
|
22
|
+
return Number.isFinite(time) ? time : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 挑出超过保留期、可以永久删除的条目。
|
|
27
|
+
* @param {Array<{ name: string, path: string, deletedAt?: number|null, bytes?: number }>} entries
|
|
28
|
+
* @param {{ nowMs?: number, retentionDays?: number }} [options]
|
|
29
|
+
* @returns {{ eligible: Array<{ name: string, path: string, deletedAt: number, bytes: number, ageDays: number }>, kept: number }}
|
|
30
|
+
*/
|
|
31
|
+
export function selectExpired(entries, options) {
|
|
32
|
+
const opts = options ?? {};
|
|
33
|
+
const nowMs = Number.isFinite(opts.nowMs) ? Number(opts.nowMs) : Date.now();
|
|
34
|
+
const retentionDays = Number.isFinite(opts.retentionDays)
|
|
35
|
+
? Math.max(0, Number(opts.retentionDays))
|
|
36
|
+
: DEFAULT_RETENTION_DAYS;
|
|
37
|
+
const cutoff = nowMs - retentionDays * DAY_MS;
|
|
38
|
+
const list = Array.isArray(entries) ? entries : [];
|
|
39
|
+
const eligible = [];
|
|
40
|
+
let kept = 0;
|
|
41
|
+
for (const entry of list) {
|
|
42
|
+
const name = String(entry?.name ?? "");
|
|
43
|
+
const path = String(entry?.path ?? "");
|
|
44
|
+
const deletedAt = Number.isFinite(entry?.deletedAt)
|
|
45
|
+
? Number(entry.deletedAt)
|
|
46
|
+
: deletedAtFromName(name);
|
|
47
|
+
if (path === "" || deletedAt === null || !Number.isFinite(deletedAt)) {
|
|
48
|
+
kept += 1; // 认不出时间的条目一律保留(宁可留着,也不猜着删)
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (deletedAt > cutoff) {
|
|
52
|
+
kept += 1;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
eligible.push({
|
|
56
|
+
name,
|
|
57
|
+
path,
|
|
58
|
+
deletedAt,
|
|
59
|
+
bytes: Math.max(0, Number(entry?.bytes ?? 0)),
|
|
60
|
+
ageDays: Math.max(0, Math.round(((nowMs - deletedAt) / DAY_MS) * 10) / 10),
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return { eligible, kept };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 删除前生成的可恢复清单(规格 §7.5 行 4c ②)。
|
|
68
|
+
* 只记录「删了什么、多大、什么时候删的」,不记录文件内容——内容本身在删之前已经要没了,
|
|
69
|
+
* 这份清单的用途是让人知道去哪找备份、以及审计能对上号。
|
|
70
|
+
* @param {{ purgedAt: string, retentionDays: number, entries: Array<{ name: string, path: string, bytes: number, ageDays: number }> }} input
|
|
71
|
+
* @returns {string}
|
|
72
|
+
*/
|
|
73
|
+
export function buildPurgeManifest(input) {
|
|
74
|
+
const entries = Array.isArray(input?.entries) ? input.entries : [];
|
|
75
|
+
const totalBytes = entries.reduce(
|
|
76
|
+
(/** @type {number} */ sum, /** @type {any} */ entry) => sum + Number(entry?.bytes ?? 0),
|
|
77
|
+
0,
|
|
78
|
+
);
|
|
79
|
+
const lines = [
|
|
80
|
+
"# 回收站清理清单",
|
|
81
|
+
"",
|
|
82
|
+
`- 清理时间:${input?.purgedAt ?? ""}`,
|
|
83
|
+
`- 保留期:${input?.retentionDays ?? DEFAULT_RETENTION_DAYS} 天`,
|
|
84
|
+
`- 条目数:${entries.length}`,
|
|
85
|
+
`- 合计体积:${totalBytes} 字节`,
|
|
86
|
+
"",
|
|
87
|
+
"## 已永久删除的条目",
|
|
88
|
+
"",
|
|
89
|
+
...entries.map(
|
|
90
|
+
(/** @type {any} */ entry) =>
|
|
91
|
+
`- \`${entry.name}\`(${entry.bytes} 字节,删除于 ${entry.ageDays} 天前)\n \`${entry.path}\``,
|
|
92
|
+
),
|
|
93
|
+
"",
|
|
94
|
+
"> 这些条目已超出保留期并被永久删除。若需要找回,只能从你自己的备份恢复。",
|
|
95
|
+
];
|
|
96
|
+
return `${lines.join("\n")}\n`;
|
|
97
|
+
}
|
package/lib/service.js
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
readdirSync,
|
|
9
9
|
readFileSync,
|
|
10
10
|
renameSync,
|
|
11
|
+
rmSync,
|
|
11
12
|
statSync,
|
|
12
13
|
writeFileSync,
|
|
13
14
|
} from "node:fs";
|
|
@@ -20,12 +21,25 @@ import { buildFixTask, errorSignature, shouldContinueFix } from "./autofix.js";
|
|
|
20
21
|
import { buildPrText, nextPrAction, parsePrNumber, planPrCreate } from "./autopr.js";
|
|
21
22
|
import { checkThreadBudget, checkTokenBudget, tokensOf } from "./budget.js";
|
|
22
23
|
import { runCommand } from "./exec.js";
|
|
23
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
checkExecutable,
|
|
26
|
+
checkMergePreflight,
|
|
27
|
+
parseRepoFromRemote,
|
|
28
|
+
planCommand,
|
|
29
|
+
recoveryEvidence,
|
|
30
|
+
shouldRetryPreflight,
|
|
31
|
+
} from "./executor.js";
|
|
32
|
+
import {
|
|
33
|
+
checkForcePushPrereqs,
|
|
34
|
+
checkProtectedPushPrereqs,
|
|
35
|
+
countCollaborators,
|
|
36
|
+
} from "./git-push.js";
|
|
24
37
|
import { appendEntry } from "./memory.js";
|
|
25
38
|
import { initialView, reduce, sortRows } from "./overview.js";
|
|
26
39
|
import { resolveDataRoot } from "./paths.js";
|
|
27
40
|
import { buildPersona } from "./persona.js";
|
|
28
41
|
import { readProjectFiles } from "./project-files.js";
|
|
42
|
+
import { buildPurgeManifest, DEFAULT_RETENTION_DAYS, selectExpired } from "./purge.js";
|
|
29
43
|
import { decideRoute } from "./routing.js";
|
|
30
44
|
import { ProjectStore } from "./store.js";
|
|
31
45
|
import { createIsolatedThread, reclaimThreadWorktree, reconcileWorktrees } from "./thread.js";
|
|
@@ -793,6 +807,149 @@ export class ProjectsService extends TypertRemoteService {
|
|
|
793
807
|
return thread;
|
|
794
808
|
}
|
|
795
809
|
|
|
810
|
+
/**
|
|
811
|
+
* 回收站保留期清理(规格 §7.5 行 4c)。
|
|
812
|
+
* 三道硬前提:开关 `purgeAfterRetention` 打开、调用方显式确认、只处理**超保留期**的条目。
|
|
813
|
+
* 默认 dry-run:只报告「会删什么」,不真删。
|
|
814
|
+
* @param {{ dryRun?: boolean, confirm?: string, retentionDays?: number, projectId?: string }} [options]
|
|
815
|
+
* @returns {{ ok: boolean, reason?: string, eligible: any[], kept: number, purged: string[], manifestPath: string|null }}
|
|
816
|
+
*/
|
|
817
|
+
purgeTrash(options) {
|
|
818
|
+
const store = this.requireStore();
|
|
819
|
+
const input = options ?? {};
|
|
820
|
+
const dryRun = input.dryRun !== false; // 省略时按 dry-run 处理,删东西必须是显式选择
|
|
821
|
+
|
|
822
|
+
/** @type {any[]} */
|
|
823
|
+
const entries = [];
|
|
824
|
+
const projects = input.projectId
|
|
825
|
+
? [store.getProject(String(input.projectId))].filter(Boolean)
|
|
826
|
+
: store.listProjects();
|
|
827
|
+
for (const project of projects) {
|
|
828
|
+
const dir = this.trashRoot();
|
|
829
|
+
if (!dir) continue;
|
|
830
|
+
let names = [];
|
|
831
|
+
try {
|
|
832
|
+
names = readdirSync(dir, { withFileTypes: true })
|
|
833
|
+
.filter((entry) => entry.isDirectory() && entry.name.startsWith(`${project.id}-`))
|
|
834
|
+
.map((entry) => entry.name);
|
|
835
|
+
} catch {
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
for (const name of names) {
|
|
839
|
+
const full = join(dir, name);
|
|
840
|
+
entries.push({ name, path: full, bytes: this.sizeOf(full) });
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const retentionDays = Number.isFinite(input.retentionDays)
|
|
845
|
+
? Number(input.retentionDays)
|
|
846
|
+
: DEFAULT_RETENTION_DAYS;
|
|
847
|
+
const { eligible, kept } = selectExpired(entries, { retentionDays });
|
|
848
|
+
|
|
849
|
+
if (dryRun) {
|
|
850
|
+
return { ok: true, eligible, kept, purged: [], manifestPath: null };
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// 真删:开关 + 显式确认
|
|
854
|
+
const switchOn = projects.some(
|
|
855
|
+
(/** @type {any} */ project) => project?.policy?.danger?.purgeAfterRetention === true,
|
|
856
|
+
);
|
|
857
|
+
if (!switchOn) {
|
|
858
|
+
store.appendAudit({ action: "trash/purge-refused", reason: "switch-off" });
|
|
859
|
+
store.save();
|
|
860
|
+
return { ok: false, reason: "switch-off", eligible, kept, purged: [], manifestPath: null };
|
|
861
|
+
}
|
|
862
|
+
if (String(input.confirm ?? "").trim() !== "purge") {
|
|
863
|
+
store.appendAudit({ action: "trash/purge-refused", reason: "confirm-required" });
|
|
864
|
+
store.save();
|
|
865
|
+
return {
|
|
866
|
+
ok: false,
|
|
867
|
+
reason: "confirm-required",
|
|
868
|
+
eligible,
|
|
869
|
+
kept,
|
|
870
|
+
purged: [],
|
|
871
|
+
manifestPath: null,
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
// ② 执行前生成可恢复清单
|
|
876
|
+
const purgedAt = new Date().toISOString();
|
|
877
|
+
const manifest = buildPurgeManifest({ purgedAt, retentionDays, entries: eligible });
|
|
878
|
+
const manifestPath = join(
|
|
879
|
+
this.dataRoot,
|
|
880
|
+
"trash",
|
|
881
|
+
`purge-${purgedAt.replace(/[:.]/gu, "-")}.md`,
|
|
882
|
+
);
|
|
883
|
+
try {
|
|
884
|
+
mkdirSync(join(this.dataRoot, "trash"), { recursive: true });
|
|
885
|
+
writeFileSync(manifestPath, manifest, { mode: 0o600 });
|
|
886
|
+
} catch (error) {
|
|
887
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
888
|
+
store.appendAudit({ action: "trash/purge-refused", reason: `manifest-failed: ${message}` });
|
|
889
|
+
store.save();
|
|
890
|
+
return {
|
|
891
|
+
ok: false,
|
|
892
|
+
reason: "manifest-failed",
|
|
893
|
+
eligible,
|
|
894
|
+
kept,
|
|
895
|
+
purged: [],
|
|
896
|
+
manifestPath: null,
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
const purged = [];
|
|
901
|
+
for (const entry of eligible) {
|
|
902
|
+
try {
|
|
903
|
+
rmSync(entry.path, { recursive: true, force: true });
|
|
904
|
+
purged.push(entry.name);
|
|
905
|
+
} catch {
|
|
906
|
+
/* 单个失败不影响其它;下面审计里会体现数量差异 */
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
store.appendAudit({
|
|
910
|
+
action: "trash/purged",
|
|
911
|
+
count: purged.length,
|
|
912
|
+
eligible: eligible.length,
|
|
913
|
+
kept,
|
|
914
|
+
retentionDays,
|
|
915
|
+
manifestPath,
|
|
916
|
+
});
|
|
917
|
+
store.save();
|
|
918
|
+
return { ok: true, eligible, kept, purged, manifestPath };
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** 回收站根目录(数据根下)。 @returns {string} */
|
|
922
|
+
trashRoot() {
|
|
923
|
+
return this.dataRoot ? join(this.dataRoot, "trash") : "";
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* 递归求目录字节数(清单里要写「删了多少」)。
|
|
928
|
+
* @param {string} dir
|
|
929
|
+
* @returns {number}
|
|
930
|
+
*/
|
|
931
|
+
sizeOf(dir) {
|
|
932
|
+
let total = 0;
|
|
933
|
+
let items = [];
|
|
934
|
+
try {
|
|
935
|
+
items = readdirSync(dir, { withFileTypes: true });
|
|
936
|
+
} catch {
|
|
937
|
+
return 0;
|
|
938
|
+
}
|
|
939
|
+
for (const item of items) {
|
|
940
|
+
const full = join(dir, item.name);
|
|
941
|
+
if (item.isDirectory()) total += this.sizeOf(full);
|
|
942
|
+
else {
|
|
943
|
+
try {
|
|
944
|
+
total += statSync(full).size;
|
|
945
|
+
} catch {
|
|
946
|
+
/* 忽略读不到的文件 */
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
return total;
|
|
951
|
+
}
|
|
952
|
+
|
|
796
953
|
/**
|
|
797
954
|
* 冷会话唤醒:启动后补发「应用关着时欠下的」协调器信封。
|
|
798
955
|
* 为什么需要:wake 原本只在 turn/end 触发;应用关着时线程跑完,协调器永远不知道。
|
|
@@ -1374,7 +1531,32 @@ export class ProjectsService extends TypertRemoteService {
|
|
|
1374
1531
|
return { executed: false, reason: "already-executed" };
|
|
1375
1532
|
}
|
|
1376
1533
|
|
|
1377
|
-
|
|
1534
|
+
// merge 的目标仓库必须**先**解析出来:早期 planCommand 就要用它,
|
|
1535
|
+
// 否则它会因为缺 repo 直接拒绝(也防止落到「宿主当前目录所在仓库」)。
|
|
1536
|
+
let mergeRepo = "";
|
|
1537
|
+
if (approval.action === "merge") {
|
|
1538
|
+
const project = store.getProject(approval.projectId);
|
|
1539
|
+
const repoDir = Array.isArray(project?.dirs) ? String(project.dirs[0] ?? "") : "";
|
|
1540
|
+
const remote =
|
|
1541
|
+
repoDir === ""
|
|
1542
|
+
? { code: 1, stdout: "", stderr: "" }
|
|
1543
|
+
: await runGit(["remote", "get-url", "origin"], repoDir);
|
|
1544
|
+
mergeRepo = remote.code === 0 ? parseRepoFromRemote(remote.stdout) : "";
|
|
1545
|
+
if (mergeRepo === "") {
|
|
1546
|
+
store.appendAudit({
|
|
1547
|
+
action: "approval/execution-refused",
|
|
1548
|
+
projectId: approval.projectId,
|
|
1549
|
+
requestId,
|
|
1550
|
+
dangerAction: approval.action,
|
|
1551
|
+
reason: "merge/repo-unknown",
|
|
1552
|
+
});
|
|
1553
|
+
store.save();
|
|
1554
|
+
return { executed: false, reason: "merge/repo-unknown" };
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
const planArgs =
|
|
1558
|
+
mergeRepo === "" ? (approval.args ?? {}) : { ...(approval.args ?? {}), repo: mergeRepo };
|
|
1559
|
+
const planned = planCommand(approval.action, planArgs);
|
|
1378
1560
|
if ("error" in planned) {
|
|
1379
1561
|
store.appendAudit({
|
|
1380
1562
|
action: "approval/execution-refused",
|
|
@@ -1407,8 +1589,91 @@ export class ProjectsService extends TypertRemoteService {
|
|
|
1407
1589
|
return { executed: false, reason: "no-worktree" };
|
|
1408
1590
|
}
|
|
1409
1591
|
const branch = String(approval.args?.branch ?? thread?.branch ?? "");
|
|
1592
|
+
const force = approval.args?.force === true;
|
|
1593
|
+
|
|
1594
|
+
if (force) {
|
|
1595
|
+
// 强推硬前提(规格 §7.5 行 1):自建且被记录、远端没被别人动过、非保护分支、旧 SHA 已知
|
|
1596
|
+
const pushProject = store.getProject(approval.projectId);
|
|
1597
|
+
const pushRepoDir = String(pushProject?.dirs?.[0] ?? "");
|
|
1598
|
+
const pushRemote =
|
|
1599
|
+
pushRepoDir === ""
|
|
1600
|
+
? { code: 1, stdout: "", stderr: "" }
|
|
1601
|
+
: await runGit(["remote", "get-url", "origin"], pushRepoDir);
|
|
1602
|
+
const pushRepo = pushRemote.code === 0 ? parseRepoFromRemote(pushRemote.stdout) : "";
|
|
1603
|
+
if (pushRepo === "") {
|
|
1604
|
+
store.appendAudit({
|
|
1605
|
+
action: "approval/execution-refused",
|
|
1606
|
+
projectId: approval.projectId,
|
|
1607
|
+
requestId,
|
|
1608
|
+
dangerAction: approval.action,
|
|
1609
|
+
reason: "force-push/repo-unknown",
|
|
1610
|
+
});
|
|
1611
|
+
store.save();
|
|
1612
|
+
return { executed: false, reason: "force-push/repo-unknown" };
|
|
1613
|
+
}
|
|
1614
|
+
const expectedSha = String(approval.args?.expectedSha ?? "");
|
|
1615
|
+
const remoteHead = await runGit(["rev-parse", `origin/${branch}`], worktree);
|
|
1616
|
+
const protectedCheck = await runGh([
|
|
1617
|
+
"api",
|
|
1618
|
+
`repos/${pushRepo}/branches/${branch}/protection`,
|
|
1619
|
+
]);
|
|
1620
|
+
const prereqs = checkForcePushPrereqs({
|
|
1621
|
+
branch,
|
|
1622
|
+
threadBranch: thread?.branch ?? null,
|
|
1623
|
+
expectedSha,
|
|
1624
|
+
remoteHeadSha: remoteHead.code === 0 ? String(remoteHead.stdout).trim() : "",
|
|
1625
|
+
lastPushedSha: thread?.lastPushedSha ?? null,
|
|
1626
|
+
protectedBranch: protectedCheck.code === 0,
|
|
1627
|
+
});
|
|
1628
|
+
if (!prereqs.ok) {
|
|
1629
|
+
store.appendAudit({
|
|
1630
|
+
action: "approval/execution-refused",
|
|
1631
|
+
projectId: approval.projectId,
|
|
1632
|
+
requestId,
|
|
1633
|
+
dangerAction: approval.action,
|
|
1634
|
+
reason: prereqs.reason,
|
|
1635
|
+
});
|
|
1636
|
+
store.save();
|
|
1637
|
+
return { executed: false, reason: prereqs.reason };
|
|
1638
|
+
}
|
|
1639
|
+
const forced = await runGit(
|
|
1640
|
+
["push", `--force-with-lease=${branch}:${expectedSha}`, "origin", branch],
|
|
1641
|
+
worktree,
|
|
1642
|
+
);
|
|
1643
|
+
const forcedOk = forced.code === 0;
|
|
1644
|
+
const forcedEvidence = recoveryEvidence(
|
|
1645
|
+
approval.action,
|
|
1646
|
+
{ branch, oldSha: expectedSha },
|
|
1647
|
+
{ stdout: forced.stdout },
|
|
1648
|
+
);
|
|
1649
|
+
store.appendAudit({
|
|
1650
|
+
action: forcedOk ? "approval/executed" : "approval/execution-failed",
|
|
1651
|
+
projectId: approval.projectId,
|
|
1652
|
+
requestId,
|
|
1653
|
+
dangerAction: approval.action,
|
|
1654
|
+
evidence: forcedEvidence,
|
|
1655
|
+
...(forcedOk ? {} : { reason: String(forced.stderr).split("\n")[0].slice(0, 200) }),
|
|
1656
|
+
});
|
|
1657
|
+
if (forcedOk) {
|
|
1658
|
+
const head = await runGit(["rev-parse", "HEAD"], worktree);
|
|
1659
|
+
if (head.code === 0) {
|
|
1660
|
+
store.setThreadWorktree(sessionId, { lastPushedSha: String(head.stdout).trim() });
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
store.save();
|
|
1664
|
+
return forcedOk
|
|
1665
|
+
? { executed: true, evidence: forcedEvidence }
|
|
1666
|
+
: { executed: false, reason: "force-push-failed" };
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1410
1669
|
const pushed = await runGit(["push", "-u", "origin", branch], worktree);
|
|
1411
1670
|
const ok = pushed.code === 0;
|
|
1671
|
+
if (ok) {
|
|
1672
|
+
const head = await runGit(["rev-parse", "HEAD"], worktree);
|
|
1673
|
+
if (head.code === 0) {
|
|
1674
|
+
store.setThreadWorktree(sessionId, { lastPushedSha: String(head.stdout).trim() });
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1412
1677
|
const evidence = recoveryEvidence(approval.action, { branch }, { stdout: pushed.stdout });
|
|
1413
1678
|
store.appendAudit({
|
|
1414
1679
|
action: ok ? "approval/executed" : "approval/execution-failed",
|
|
@@ -1437,10 +1702,188 @@ export class ProjectsService extends TypertRemoteService {
|
|
|
1437
1702
|
return { executed: true, evidence };
|
|
1438
1703
|
}
|
|
1439
1704
|
|
|
1705
|
+
// 直推保护/默认分支(规格 §7.5 行 2):per-repo 首次授予 + 服务端允许 + 审计/事后通知
|
|
1706
|
+
if (approval.action === "push-protected-branch") {
|
|
1707
|
+
const branch = String(approval.args?.branch ?? "");
|
|
1708
|
+
const grProject = store.getProject(approval.projectId);
|
|
1709
|
+
const grDir = String(grProject?.dirs?.[0] ?? "");
|
|
1710
|
+
const grRemote =
|
|
1711
|
+
grDir === ""
|
|
1712
|
+
? { code: 1, stdout: "", stderr: "" }
|
|
1713
|
+
: await runGit(["remote", "get-url", "origin"], grDir);
|
|
1714
|
+
const grRepo = grRemote.code === 0 ? parseRepoFromRemote(grRemote.stdout) : "";
|
|
1715
|
+
if (grRepo === "") {
|
|
1716
|
+
store.appendAudit({
|
|
1717
|
+
action: "approval/execution-refused",
|
|
1718
|
+
projectId: approval.projectId,
|
|
1719
|
+
requestId,
|
|
1720
|
+
dangerAction: approval.action,
|
|
1721
|
+
reason: "protected-push/repo-unknown",
|
|
1722
|
+
});
|
|
1723
|
+
store.save();
|
|
1724
|
+
return { executed: false, reason: "protected-push/repo-unknown" };
|
|
1725
|
+
}
|
|
1726
|
+
// ① per-repo 首次授予:只有项目策略里显式列出的仓库才允许
|
|
1727
|
+
if (grProject?.policy?.repoGrants?.[grRepo] !== true) {
|
|
1728
|
+
store.appendAudit({
|
|
1729
|
+
action: "approval/execution-refused",
|
|
1730
|
+
projectId: approval.projectId,
|
|
1731
|
+
requestId,
|
|
1732
|
+
dangerAction: approval.action,
|
|
1733
|
+
reason: "protected-push/repo-not-granted",
|
|
1734
|
+
repo: grRepo,
|
|
1735
|
+
});
|
|
1736
|
+
store.save();
|
|
1737
|
+
return { executed: false, reason: "protected-push/repo-not-granted" };
|
|
1738
|
+
}
|
|
1739
|
+
// ② 服务端必须允许直接推:查 protection 与 rulesets
|
|
1740
|
+
const protection = await runGh(["api", `repos/${grRepo}/branches/${branch}/protection`]);
|
|
1741
|
+
const rulesets = await runGh(["api", `repos/${grRepo}/rulesets`]);
|
|
1742
|
+
let parsedRulesets = [];
|
|
1743
|
+
if (rulesets.code === 0) {
|
|
1744
|
+
try {
|
|
1745
|
+
parsedRulesets = JSON.parse(rulesets.stdout);
|
|
1746
|
+
} catch {
|
|
1747
|
+
parsedRulesets = [];
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
const allowed = checkProtectedPushPrereqs({
|
|
1751
|
+
protection:
|
|
1752
|
+
protection.code === 0
|
|
1753
|
+
? (() => {
|
|
1754
|
+
try {
|
|
1755
|
+
return JSON.parse(protection.stdout);
|
|
1756
|
+
} catch {
|
|
1757
|
+
return null;
|
|
1758
|
+
}
|
|
1759
|
+
})()
|
|
1760
|
+
: null,
|
|
1761
|
+
rulesets: parsedRulesets,
|
|
1762
|
+
});
|
|
1763
|
+
if (!allowed.ok) {
|
|
1764
|
+
store.appendAudit({
|
|
1765
|
+
action: "approval/execution-refused",
|
|
1766
|
+
projectId: approval.projectId,
|
|
1767
|
+
requestId,
|
|
1768
|
+
dangerAction: approval.action,
|
|
1769
|
+
reason: allowed.reason,
|
|
1770
|
+
});
|
|
1771
|
+
store.save();
|
|
1772
|
+
return { executed: false, reason: allowed.reason };
|
|
1773
|
+
}
|
|
1774
|
+
// ③ 多人协作检测:不禁止,但要在审计与返回里显式警告
|
|
1775
|
+
const commits = await runGh(["api", `repos/${grRepo}/commits?per_page=30`]);
|
|
1776
|
+
/** @type {{ collaborators: number, multi: boolean, sample: string[] }} */
|
|
1777
|
+
let collab = { collaborators: 0, multi: false, sample: [] };
|
|
1778
|
+
if (commits.code === 0) {
|
|
1779
|
+
try {
|
|
1780
|
+
collab = countCollaborators(JSON.parse(commits.stdout));
|
|
1781
|
+
} catch {
|
|
1782
|
+
/* 拿不到就按单人处理,但下面仍会记一条审计 */
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
const pushedProtected = await runGit(["push", "origin", branch], grDir);
|
|
1786
|
+
const okProtected = pushedProtected.code === 0;
|
|
1787
|
+
const evidence = recoveryEvidence(
|
|
1788
|
+
approval.action,
|
|
1789
|
+
{ branch, repo: grRepo },
|
|
1790
|
+
{ stdout: pushedProtected.stdout },
|
|
1791
|
+
);
|
|
1792
|
+
store.appendAudit({
|
|
1793
|
+
action: okProtected ? "approval/executed" : "approval/execution-failed",
|
|
1794
|
+
projectId: approval.projectId,
|
|
1795
|
+
requestId,
|
|
1796
|
+
dangerAction: approval.action,
|
|
1797
|
+
repo: grRepo,
|
|
1798
|
+
branch,
|
|
1799
|
+
evidence,
|
|
1800
|
+
collaborators: collab.collaborators,
|
|
1801
|
+
...(collab.multi ? { warning: "multi-collaborator" } : {}),
|
|
1802
|
+
...(okProtected
|
|
1803
|
+
? {}
|
|
1804
|
+
: { reason: String(pushedProtected.stderr).split("\n")[0].slice(0, 200) }),
|
|
1805
|
+
});
|
|
1806
|
+
store.save();
|
|
1807
|
+
return okProtected
|
|
1808
|
+
? {
|
|
1809
|
+
executed: true,
|
|
1810
|
+
evidence,
|
|
1811
|
+
...(collab.multi
|
|
1812
|
+
? { warning: "multi-collaborator", collaborators: collab.collaborators }
|
|
1813
|
+
: {}),
|
|
1814
|
+
}
|
|
1815
|
+
: { executed: false, reason: "protected-push-failed" };
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1440
1818
|
// merge:走 gh pr merge(argv 里已含 --squash,不带 --admin/--force)。
|
|
1441
1819
|
// 只合并我们自己的 PR:planCommand 已保证 PR 号是正整数,且危险开关与阈值都过了。
|
|
1442
1820
|
if (approval.action === "merge") {
|
|
1443
|
-
const
|
|
1821
|
+
const prNumber = Number(approval.args?.prNumber);
|
|
1822
|
+
const repo = mergeRepo;
|
|
1823
|
+
|
|
1824
|
+
// 前置校验:非 draft、可合并、仍 open(规格 §7.5 行 3 的硬前提)
|
|
1825
|
+
const view = await runGh([
|
|
1826
|
+
"pr",
|
|
1827
|
+
"view",
|
|
1828
|
+
String(prNumber),
|
|
1829
|
+
"--repo",
|
|
1830
|
+
repo,
|
|
1831
|
+
"--json",
|
|
1832
|
+
"isDraft,mergeable,state",
|
|
1833
|
+
]);
|
|
1834
|
+
if (view.code !== 0) {
|
|
1835
|
+
store.appendAudit({
|
|
1836
|
+
action: "approval/execution-failed",
|
|
1837
|
+
projectId: approval.projectId,
|
|
1838
|
+
requestId,
|
|
1839
|
+
dangerAction: approval.action,
|
|
1840
|
+
reason: String(view.stderr).split("\n")[0].slice(0, 200) || "merge/pr-view-failed",
|
|
1841
|
+
});
|
|
1842
|
+
store.save();
|
|
1843
|
+
return { executed: false, reason: "merge/pr-view-failed" };
|
|
1844
|
+
}
|
|
1845
|
+
const parsed = (() => {
|
|
1846
|
+
try {
|
|
1847
|
+
return JSON.parse(view.stdout);
|
|
1848
|
+
} catch {
|
|
1849
|
+
return null;
|
|
1850
|
+
}
|
|
1851
|
+
})();
|
|
1852
|
+
// GitHub 刚建 PR 时 mergeable 可能是 UNKNOWN(服务端还在算):有界重试几次。
|
|
1853
|
+
let preflight = checkMergePreflight(parsed);
|
|
1854
|
+
let attempt = 0;
|
|
1855
|
+
while (!preflight.ok && shouldRetryPreflight(preflight.reason ?? "") && attempt < 5) {
|
|
1856
|
+
attempt += 1;
|
|
1857
|
+
await new Promise((resolve) => setTimeout(resolve, 2000));
|
|
1858
|
+
const again = await runGh([
|
|
1859
|
+
"pr",
|
|
1860
|
+
"view",
|
|
1861
|
+
String(prNumber),
|
|
1862
|
+
"--repo",
|
|
1863
|
+
repo,
|
|
1864
|
+
"--json",
|
|
1865
|
+
"isDraft,mergeable,state",
|
|
1866
|
+
]);
|
|
1867
|
+
if (again.code !== 0) break;
|
|
1868
|
+
try {
|
|
1869
|
+
preflight = checkMergePreflight(JSON.parse(again.stdout));
|
|
1870
|
+
} catch {
|
|
1871
|
+
break;
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
if (!preflight.ok) {
|
|
1875
|
+
store.appendAudit({
|
|
1876
|
+
action: "approval/execution-refused",
|
|
1877
|
+
projectId: approval.projectId,
|
|
1878
|
+
requestId,
|
|
1879
|
+
dangerAction: approval.action,
|
|
1880
|
+
reason: preflight.reason,
|
|
1881
|
+
});
|
|
1882
|
+
store.save();
|
|
1883
|
+
return { executed: false, reason: preflight.reason };
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
const ghArgs = planned.argv.slice(1); // 去掉 argv[0] 的 "gh"(planArgs 已带 --repo)
|
|
1444
1887
|
const merged = await runGh(ghArgs);
|
|
1445
1888
|
const ok = merged.code === 0;
|
|
1446
1889
|
const evidence = recoveryEvidence(approval.action, approval.args ?? {}, {
|
|
@@ -1674,6 +2117,7 @@ declareRemote(ProjectsService, "resumeProject");
|
|
|
1674
2117
|
declareRemote(ProjectsService, "archiveProject");
|
|
1675
2118
|
declareRemote(ProjectsService, "unarchiveProject");
|
|
1676
2119
|
declareRemote(ProjectsService, "reconcileWakes");
|
|
2120
|
+
declareRemote(ProjectsService, "purgeTrash");
|
|
1677
2121
|
declareRemote(ProjectsService, "previewDeleteProject");
|
|
1678
2122
|
declareRemote(ProjectsService, "deleteProject");
|
|
1679
2123
|
declareRemote(ProjectsService, "attachThread");
|
package/lib/store.js
CHANGED
|
@@ -19,6 +19,7 @@ export const FORMAT_VERSION = 1;
|
|
|
19
19
|
* @property {Record<string, boolean>} danger 危险动作开关,默认全 false
|
|
20
20
|
* @property {{ rules: any[], fallback: boolean }} routing 路由规则(扁平结构)与是否允许模型兜底
|
|
21
21
|
* @property {string} persona 协调器人格;空串表示用内置默认人格
|
|
22
|
+
* @property {Record<string, true>} repoGrants 直推保护分支的 per-repo 首次授予
|
|
22
23
|
*/
|
|
23
24
|
|
|
24
25
|
/**
|
|
@@ -40,6 +41,8 @@ export const FORMAT_VERSION = 1;
|
|
|
40
41
|
* @property {string} projectId
|
|
41
42
|
* @property {'idle'|'working'|'waiting'|'done'|'failed'} state
|
|
42
43
|
* @property {string|null} branch
|
|
44
|
+
* @property {string|null} lastPushedSha
|
|
45
|
+
* @property {string|null} baseSha
|
|
43
46
|
* @property {string|null} worktree
|
|
44
47
|
* @property {number} seq
|
|
45
48
|
*/
|
|
@@ -64,6 +67,8 @@ export function defaultPolicy() {
|
|
|
64
67
|
routing: { rules: defaultRules(), fallback: true },
|
|
65
68
|
// 协调器人格;空串表示用内置默认人格
|
|
66
69
|
persona: "",
|
|
70
|
+
// 直推保护分支的 per-repo 首次授予:只有显式 true 的仓库才允许
|
|
71
|
+
repoGrants: {},
|
|
67
72
|
};
|
|
68
73
|
}
|
|
69
74
|
|
|
@@ -104,6 +109,19 @@ export function normalizePolicy(raw, fallbackPolicy) {
|
|
|
104
109
|
: typeof previous.persona === "string"
|
|
105
110
|
? previous.persona
|
|
106
111
|
: "",
|
|
112
|
+
// 只接受显式 true 的仓库授权;其它写法一律当没授权
|
|
113
|
+
repoGrants: (() => {
|
|
114
|
+
const pick = (/** @type {any} */ source) =>
|
|
115
|
+
source && typeof source === "object" && !Array.isArray(source)
|
|
116
|
+
? Object.fromEntries(
|
|
117
|
+
Object.entries(source).filter(
|
|
118
|
+
([key, value]) => typeof key === "string" && value === true,
|
|
119
|
+
),
|
|
120
|
+
)
|
|
121
|
+
: {};
|
|
122
|
+
const fromPolicy = pick(policy.repoGrants);
|
|
123
|
+
return Object.keys(fromPolicy).length > 0 ? fromPolicy : pick(previous.repoGrants);
|
|
124
|
+
})(),
|
|
107
125
|
};
|
|
108
126
|
}
|
|
109
127
|
|
|
@@ -183,6 +201,8 @@ export function normalize(raw, root) {
|
|
|
183
201
|
? thread.state
|
|
184
202
|
: "idle",
|
|
185
203
|
branch: typeof thread.branch === "string" ? thread.branch : null,
|
|
204
|
+
lastPushedSha: typeof thread.lastPushedSha === "string" ? thread.lastPushedSha : null,
|
|
205
|
+
baseSha: typeof thread.baseSha === "string" ? thread.baseSha : null,
|
|
186
206
|
worktree: typeof thread.worktree === "string" ? thread.worktree : null,
|
|
187
207
|
seq: Number.isInteger(thread.seq) ? thread.seq : 0,
|
|
188
208
|
createdAt: typeof thread.createdAt === "string" ? thread.createdAt : iso(),
|
|
@@ -372,12 +392,15 @@ export class ProjectStore {
|
|
|
372
392
|
/**
|
|
373
393
|
* 记录线程的 worktree 归属(建 worktree 成功后调用)。
|
|
374
394
|
* @param {string} sessionId
|
|
375
|
-
* @param {{ branch?: string|null, worktree?: string|null, baseSha?: string|null, state?: string }} patch
|
|
395
|
+
* @param {{ branch?: string|null, worktree?: string|null, baseSha?: string|null, lastPushedSha?: string|null, state?: string }} patch
|
|
376
396
|
*/
|
|
377
397
|
setThreadWorktree(sessionId, patch) {
|
|
378
398
|
const current = this.state.threads[sessionId];
|
|
379
399
|
if (!current) throw new Error(`projects: unknown thread ${sessionId}`);
|
|
380
400
|
if (typeof patch.branch === "string" || patch.branch === null) current.branch = patch.branch;
|
|
401
|
+
if (typeof patch.lastPushedSha === "string" || patch.lastPushedSha === null) {
|
|
402
|
+
current.lastPushedSha = patch.lastPushedSha;
|
|
403
|
+
}
|
|
381
404
|
if (typeof patch.worktree === "string" || patch.worktree === null)
|
|
382
405
|
current.worktree = patch.worktree;
|
|
383
406
|
if (typeof patch.baseSha === "string" || patch.baseSha === null)
|
package/lib/tools.js
CHANGED
package/locale/en.json
CHANGED
|
@@ -76,16 +76,16 @@
|
|
|
76
76
|
"settings.fallback": "Allow the model to propose when no rule matches",
|
|
77
77
|
"settings.dangerTitle": "Danger switches (all off by default)",
|
|
78
78
|
"settings.dangerHint": "Every switch needs your explicit consent; the plugin never turns one on by itself.",
|
|
79
|
-
"settings.danger.forcePushOwnBranch.label": "Allow pushing your own dsh/ branches
|
|
80
|
-
"settings.danger.forcePushOwnBranch.risk": "
|
|
81
|
-
"settings.danger.pushProtectedBranch.label": "Allow pushing to protected branches
|
|
82
|
-
"settings.danger.pushProtectedBranch.risk": "
|
|
79
|
+
"settings.danger.forcePushOwnBranch.label": "Allow force-pushing your own dsh/ branches",
|
|
80
|
+
"settings.danger.forcePushOwnBranch.risk": "Uses --force-with-lease bound to the expected SHA; refuses when the remote moved, the branch is protected, or the old SHA is unknown, and records the old SHA for recovery.",
|
|
81
|
+
"settings.danger.pushProtectedBranch.label": "Allow pushing directly to default/protected branches",
|
|
82
|
+
"settings.danger.pushProtectedBranch.risk": "Requires a per-repo grant in the project policy; checks protection/rulesets first and refuses when the server requires a PR; every push is audited and multi-collaborator repos raise a warning.",
|
|
83
83
|
"settings.danger.autoMerge.label": "auto-merge PRs",
|
|
84
84
|
"settings.danger.autoMerge.risk": "merging is irreversible (revert only); still gated by diff limits and human approval",
|
|
85
85
|
"settings.danger.trashAuto.label": "auto archive/delete into trash",
|
|
86
86
|
"settings.danger.trashAuto.risk": "moves content into trash/; restorable from manifest, but not free",
|
|
87
|
-
"settings.danger.purgeAfterRetention.label": "Allow purging the trash after retention
|
|
88
|
-
"settings.danger.purgeAfterRetention.risk": "
|
|
87
|
+
"settings.danger.purgeAfterRetention.label": "Allow purging the trash after the retention period",
|
|
88
|
+
"settings.danger.purgeAfterRetention.risk": "Only touches entries already in the trash that exceed the retention period; writes a purge manifest first; dry-run by default, real deletion needs explicit confirmation.",
|
|
89
89
|
"settings.danger.editProfile.label": "edit project policy itself",
|
|
90
90
|
"settings.danger.editProfile.risk": "the coordinator could loosen its own limits; highest risk",
|
|
91
91
|
"detail.archive": "Archive project",
|
package/locale/zh.json
CHANGED
|
@@ -76,16 +76,16 @@
|
|
|
76
76
|
"settings.fallback": "规则都不命中时允许模型兜底提议",
|
|
77
77
|
"settings.dangerTitle": "危险动作开关(默认全关)",
|
|
78
78
|
"settings.dangerHint": "打开任何一个开关都需要你明确同意;插件不会自行打开。",
|
|
79
|
-
"settings.danger.forcePushOwnBranch.label": "
|
|
80
|
-
"settings.danger.forcePushOwnBranch.risk": "
|
|
81
|
-
"settings.danger.pushProtectedBranch.label": "
|
|
82
|
-
"settings.danger.pushProtectedBranch.risk": "
|
|
79
|
+
"settings.danger.forcePushOwnBranch.label": "允许强推自己的 dsh/ 分支",
|
|
80
|
+
"settings.danger.forcePushOwnBranch.risk": "用 --force-with-lease 绑定期望 SHA;远端被他人动过、分支受保护、旧 SHA 未知时一律拒绝,并记旧 SHA 供恢复。",
|
|
81
|
+
"settings.danger.pushProtectedBranch.label": "允许直推默认/保护分支",
|
|
82
|
+
"settings.danger.pushProtectedBranch.risk": "需要先在项目策略里对该仓库 per-repo 授予;推前查 protection/rulesets,服务端要求 PR 时直接拒;每次审计,检测到多人协作会额外警告。",
|
|
83
83
|
"settings.danger.autoMerge.label": "允许自动合并 PR",
|
|
84
84
|
"settings.danger.autoMerge.risk": "合并不可逆(只能用 revert 回退);仍受 diff 阈值与人工批准约束",
|
|
85
85
|
"settings.danger.trashAuto.label": "允许自动归档/删除到回收站",
|
|
86
86
|
"settings.danger.trashAuto.risk": "会把内容移入 trash/;可从 manifest 恢复,但不是零成本",
|
|
87
|
-
"settings.danger.purgeAfterRetention.label": "
|
|
88
|
-
"settings.danger.purgeAfterRetention.risk": "
|
|
87
|
+
"settings.danger.purgeAfterRetention.label": "允许保留期后清理回收站",
|
|
88
|
+
"settings.danger.purgeAfterRetention.risk": "只处理已在回收站且超过保留期的条目;执行前生成清理清单;默认 dry-run,真删需显式确认。",
|
|
89
89
|
"settings.danger.editProfile.label": "允许修改项目策略本身",
|
|
90
90
|
"settings.danger.editProfile.risk": "协调器可能借此放宽自己的限制;风险最高",
|
|
91
91
|
"detail.archive": "归档项目",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kangyishuai/dsh-projects",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Project-level context for DeepSeek Harness: group sessions into projects, inject instructions and memory, run isolated parallel threads, and coordinate them with an optional auditable coordinator.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|