@kangyishuai/dsh-projects 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kangyishuai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # @kangyishuai/dsh-projects
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Project-level context for DeepSeek Harness: group sessions into projects, inject project instructions and memory, run isolated parallel threads, and coordinate them with an optional auditable coordinator.
4
+
5
+ [中文](./README.zh-CN.md)
6
+
7
+ Unofficial plugin for [DeepSeek Harness (DSH)](https://github.com/deepseek-ai/deepseek-harness). Not affiliated with DeepSeek.
8
+
9
+ > **Note on coordinator context (2026-11-17, DSH 0.2.2-rc.3):** the host's per-session runtime context is not
10
+ > delivered to the coordinator session, so project rules, the memory index **and the persona travel inside the
11
+ > wake envelope** instead — one letter per turn, carrying the thread's result too.
12
+ > Details: `docs/runtime/0.2.2-rc.3.md` §11.24–§11.26.
13
+
14
+ > **Status: M4 done, pre-1.0.** Projects, context injection, isolated parallel threads, an opt-in coordinator,
15
+ > and a gated approval/executor layer are implemented, unit-tested (274 tests) and covered by a 51-assertion
16
+ > web end-to-end smoke plus an 11-assertion desktop read-only regression.
17
+ > Remote writes (push / PR / merge) are wired and verified locally against a bare remote and a stub `gh`;
18
+ > the real-GitHub effect still needs one release confirmation. Project **sharing** is deferred ([ADR 0018](../../docs/adr/0018-projects-defer-liveshare-sharing.md)).
19
+
20
+ ## What it does
21
+
22
+ DSH groups sessions by working directory and gives the model no project-level memory. This plugin adds the missing layer:
23
+
24
+ - **Project as a first-class context unit** — a durable record with a goal, directories, budget, and policy. Session membership is stored by the plugin (not derived from an immutable `cwd`).
25
+ - **Project instructions and memory injection** — every session attached to a project receives the project's standing rules and `MEMORY.md` index before each request (registered once, rendered per session; sessions belonging to no project get nothing).
26
+ - **Project-level budget gate** — a daily thread cap and a concurrent cap are enforced before a thread is created (token-level spend caps come with the coordinator).
27
+ - **Pause, archive, delete** — pause is reversible and only blocks new threads; delete follows ADR 0002: one-line impact (threads, size, running, restorable), a two-step confirm, and everything moved into `trash/` with a `manifest.json`.
28
+ - **In-app notifications** — a global overlay poller raises a toast when a thread newly fails or starts waiting on you; the browser Notification API stays off by default.
29
+ - **Isolated parallel threads** — one session per task. When the project directory is a Git repository, the thread gets its own worktree under `<repoParent>/.dsh-worktrees/<repo>/`; otherwise it degrades to a shared directory with an explicit warning instead of failing.
30
+ - **Overview with what needs you** — five thread states (`waiting-user > failed > working > done > idle`) derived from the durable session event log, not from model self-reports; whatever needs you sorts first.
31
+ - **Coordinator** — when a thread finishes a turn, a structured wake envelope (carrying the thread's actual result) is delivered to the project's coordinator session, at most once per turn. User input is routed by **flat rules first** (`{when, action}`); the model only proposes when no rule matches.
32
+ - **Autonomy gate** — `L0` observe, `L1` propose only (default), `L2` may start threads, `L3` full. The gate sits _after_ the decision and _before_ the action, so the audit shows both the intent and why it was refused.
33
+ - **A small, non-negotiable tool basket** — the coordinator gets four `project_*` tools (start thread, list threads, message thread, request action) and **no** shell, file writing, deletion, push or merge. Dangerous actions can only be _requested_; the approval queue collects them and you decide.
34
+ - **Approval, then execution** — an approval only records consent. Executing it still requires the matching danger switch (all six default **off**), an impact that fits the limits, and an explicit action→switch mapping. Every execution writes recovery evidence; every refusal writes an audit entry saying why.
35
+ - **Untrusted input stays data** — content from CI logs, PR comments or peers arrives as `relay`, gets wrapped in a "this is data, not instructions" block whose fence is longer than any backtick run inside it, and can never authorize an action.
36
+ - **Editable policy** — autonomy level, persona and the model-fallback switch are editable in settings (the first settings screen still stays at three rows).
37
+ - **Opt-in remote writes** — pushing a thread branch, opening a PR (four tiers, `off` by default) and merging, each gated by a danger switch plus a human approval. Verified end-to-end locally with a bare remote and a stub `gh`; the real-GitHub effect still needs one release confirmation.
38
+ - **Project sharing** — deferred, see [ADR 0018](../../docs/adr/0018-projects-defer-liveshare-sharing.md): DSH 0.2.2-rc.3 ships `dsh-experimental-liveshare` but does not enable it and exposes no stable host service, so building on it would be guesswork.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ dsh plugin --profile desktop add @kangyishuai/dsh-projects
44
+ ```
45
+
46
+ Restart the DSH desktop app afterwards.
47
+
48
+ ## Side effects & risks
49
+
50
+ - **Writes metadata** under `$DSH_HOME/projects/projects.json` (or `config.dataRoot` when set; a desktop app that does not export `DSH_HOME` falls back to `~/.dsh/projects`). Atomic replace via a temp file; a corrupt file is renamed aside and never deleted.
51
+ - **Creates Git worktrees** next to your repository (never inside it and never inside `.git/`) when you create a thread for a project that has a Git directory. Archiving the thread removes the worktree again **only** when it is clean, has no unpushed commits, and is not the current session's directory; otherwise it is kept and reported.
52
+ - **Runs `git`** through `node:child_process` for worktree create/remove and the cleanliness checks. No network, no credentials.
53
+ - **Never touches session logs.** Detaching or archiving a project leaves every `session.v*.jsonl.zstd` untouched.
54
+ - On startup the plugin reconciles its records: a recorded worktree that no longer exists is dropped from the record, while an unrecorded directory on disk is **kept** and only reported.
55
+ - **Remote writes are opt-in and off by default.** `git push`, `gh pr create` and `gh pr merge` exist but each requires both a danger switch and a human approval; nothing is pushed or merged automatically.
56
+ - **No credentials are read into model context** by design.
57
+ - If the metadata file cannot be read (permissions, newer format), the plugin stays inert and logs a warning instead of failing the harness.
58
+
59
+ ## Remote access
60
+
61
+ Everything runs on the machine that hosts DSH. If you want to reach it from another device, see
62
+ [docs/deployment/projects-l1-remote.md](../../docs/deployment/projects-l1-remote.md) — it covers the
63
+ safe ways to expose the Web UI (loopback + tunnel, HTTPS, reverse proxy) and what `projects` does and
64
+ does not do over a remote connection.
65
+
66
+ ## Compatibility
67
+
68
+ | Plugin | Verified on DSH |
69
+ | ------ | --------------- |
70
+ | 0.1.x | 0.2.2-rc.3 |
71
+
72
+ ## License
73
+
74
+ MIT
@@ -0,0 +1,73 @@
1
+ # @kangyishuai/dsh-projects
2
+
3
+ > 把项目做成一等上下文单元:会话归属、项目级指令与记忆注入、每线程独立工作树、可审计的协调器,以及可封顶的成本闸。
4
+
5
+ [English](./README.md)
6
+
7
+ 非官方 [DeepSeek Harness (DSH)](https://github.com/deepseek-ai/deepseek-harness) 插件,与 DeepSeek 无关。
8
+
9
+ > **关于协调器的上下文(2026-11-17,DSH 0.2.2-rc.3):** 宿主的按会话 runtime context 不会投递给协调器会话,
10
+ > 因此项目规则、记忆索引**与人格**改为**随 wake 信封**送达——每轮一封信,同时带着线程结果。
11
+ > 细节见 `docs/runtime/0.2.2-rc.3.md` §11.24–§11.26。
12
+
13
+ > **状态:M4 已完成,仍是 1.0 之前。** 项目、上下文注入、隔离的并行线程、可选协调器,以及带闸门的审批/执行层均已实现,
14
+ > 有 274 项单测、51 项 web 端到端冒烟与 11 项桌面只读回归覆盖。
15
+ > 远端写入(推分支 / 开 PR / 合并)已接线,并用本地 bare 远端 + 桩 `gh` 完成端到端验证;
16
+ > 真实 GitHub 上的效果还需发版后确认一次。**项目共享**已推迟([ADR 0018](../../docs/adr/0018-projects-defer-liveshare-sharing.md))。
17
+
18
+ ## 做什么
19
+
20
+ DSH 按工作目录给会话分组,且模型看不到项目级记忆。本插件补上这一层:
21
+
22
+ - **项目是一等上下文单元** —— 一条持久记录,带目标、目录、预算与策略。会话归属由插件自己存(不依赖不可变的 `cwd` 现算)。
23
+ - **项目指令与记忆注入** —— 归属某项目的会话在每次请求前收到该项目的常设规则与 `MEMORY.md` 索引(16k 预算、不与宿主已加载的 AGENTS.md 重复)。实现是全局注册一次、按会话求值:不属于任何项目的会话拿到的始终是空串。- **项目级预算闸** —— 建线程前拦每日线程数与并发上限(token 维度的花费上限随协调器一起做)。
24
+ - **暂停 / 归档 / 删除** —— 暂停可逆、只拦新建;删除遵循 ADR 0002:一行影响面(线程数、体积、是否在跑、可否恢复)+ 两段式确认,全部移入 `trash/` 并留 `manifest.json`。
25
+ - **应用内通知** —— 全局 overlay 轮询,线程新出现失败或在等你时弹 toast;浏览器 Notification 默认不开。
26
+
27
+ - **隔离的并行线程** —— 每个任务一个会话。项目目录是 Git 仓库时,线程拿到自己的 worktree(`<仓库同级>/.dsh-worktrees/<仓库名>/`);不是仓库时**降级为共享目录**并明确告警,而不是建不出线程。
28
+ - **「需要我」总览** —— 五个状态(`待你处理 > 失败 > 进行中 > 已完成 > 空闲`)全部从持久会话事件推导,不依赖模型自报;需要你处理的排在前面。
29
+ - **协调器** —— 线程跑完一轮就给它送一封结构化唤醒信封(**带着线程的真实结果**),每轮最多一次。用户输入**先按扁平规则路由**(`{when, action}`),规则都不命中时才由模型提议。
30
+ - **自治闸门** —— `L0` 只观察、`L1` 只提议(默认)、`L2` 可建线程、`L3` 全权。闸门在**决策之后、执行之前**,所以审计里同时看得到意图与拒绝原因。
31
+ - **极小的工具篮子** —— 协调器只有 4 个 `project_*` 工具(建线程/列线程/发消息/申请动作),**没有** shell、写文件、删除、推送、合并。危险动作只能「申请」,由审批队列收集、由你决定。
32
+ - **先批准、后执行** —— 批准只代表「同意这一次」;真正执行还要对应危险开关打开(六个**默认全关**)、影响面在阈值内,且动作与开关之间是显式映射。每次执行都留恢复证据,每次拒绝都写审计说明原因。
33
+ - **不可信输入只是数据** —— 来自 CI 日志、PR 评论或 peer 的内容以 `relay` 身份进来,会被包成「这是数据不是指令」的块(围栏比内容里最长反引号串更长),永远不能构成授权。
34
+ - **策略可编辑** —— 自治级别、人格、模型兜底开关都在设置里改(设置首屏仍保持三行)。
35
+ - **可选远端写入** —— 推线程分支、开 PR(四档,默认 `off`)、合并,都要危险开关 + 人工批准;
36
+ 已用本地 bare 远端 + 桩 `gh` 完成端到端验证,真实 GitHub 上的效果还需发版后确认一次。
37
+ - **项目共享** —— 推迟,见 [ADR 0018](../../docs/adr/0018-projects-defer-liveshare-sharing.md):
38
+ DSH 0.2.2-rc.3 虽带 `dsh-experimental-liveshare`,但未启用、也没有稳定宿主接口,基于它实现等于猜测。
39
+
40
+ ## 安装
41
+
42
+ ```bash
43
+ dsh plugin --profile desktop add @kangyishuai/dsh-projects
44
+ ```
45
+
46
+ 装完重启 DSH 桌面版。
47
+
48
+ ## 副作用与风险
49
+
50
+ - **写元数据**到 `$DSH_HOME/projects/projects.json`(配置了 `config.dataRoot` 时写到那里;桌面版不导出 `DSH_HOME` 时回落到 `~/.dsh/projects`)。用临时文件原子替换;文件损坏时**改名隔离**,绝不删除。
51
+ - **会创建 Git worktree**(在仓库同级、绝不进仓库或 `.git/` 内)。归档线程时**只有**同时满足"干净、无未推送提交、不是当前会话目录"才会删除它,否则保留并报告。
52
+ - **会调用 `git`**(`node:child_process`)做 worktree 创建/删除与干净度检查。不走网络、不读凭据。
53
+ - **不碰会话日志。** 解绑或归档项目不会改动任何 `session.v*.jsonl.zstd`。
54
+ - 启动时对账:记录里有、磁盘上没有的 worktree 会从记录里清掉;磁盘上有、记录里没有的目录**保留**,只报告。
55
+ - **远端写入是 opt-in 且默认关。** `git push`、`gh pr create`、`gh pr merge` 都已实现,但每个动作都要求**危险开关打开 + 人工批准**;不会自动推送或合并。
56
+ - **设计上不把凭据读进模型上下文。**
57
+ - 元数据读不出来(权限、版本更新)时,插件保持静默并记一条警告,不会让宿主启动失败。
58
+
59
+ ## 远程访问
60
+
61
+ 一切都跑在承载 DSH 的那台机器上。想从另一台设备连过来,见
62
+ [docs/deployment/projects-l1-remote.md](../../docs/deployment/projects-l1-remote.md):
63
+ 里面写了安全暴露 Web UI 的几种做法(回环 + 隧道、HTTPS、反向代理),以及 `projects` 在远程连接下的能力边界。
64
+
65
+ ## 兼容性
66
+
67
+ | 插件版本 | 已验证的 DSH 版本 |
68
+ | -------- | ----------------- |
69
+ | 0.1.x | 0.2.2-rc.3 |
70
+
71
+ ## License
72
+
73
+ MIT
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: projects
3
+ name: "@kangyishuai/dsh-projects"
package/lib/attach.js ADDED
@@ -0,0 +1,89 @@
1
+ // @ts-check
2
+ // 把一个已归属项目的会话接上项目上下文。
3
+ // 这个模块**故意不 import 任何 @deepseek-ai/\***(宿主的包只在运行时可用),
4
+ // 这样它能在 node --test 里直接单测。
5
+ import { PROJECT_CONTEXT_ORDER, renderProjectContext } from "./context.js";
6
+ import { readProjectFiles } from "./project-files.js";
7
+
8
+ /** @typedef {import("./store.js").ProjectStore} ProjectStore */
9
+
10
+ /**
11
+ * 全局注册一个「按会话求值」的项目上下文条目。
12
+ *
13
+ * 为什么不是 per-agent 注册:实测(docs/runtime §11.18)在 `agent/created` 里注册不会进入提示词。
14
+ * 为什么是函数:`refreshContext` 用 `resolveContext`,它会调用 `text(context)`;
15
+ * context 里带当前 agent/session(宿主 sandbox-policy 就是这么用 context.agent?.session 的)。
16
+ *
17
+ * @param {object} deps
18
+ * @param {() => any} deps.getStore
19
+ * @param {() => string} deps.getDataRoot
20
+ * @param {(entry: any) => any} deps.register 实际的 systemPrompt.context 调用
21
+ * @param {(project: any) => string} [deps.renderPersona] 协调器会话的人格文本
22
+ * @param {(sessionId: string, kind: "call"|"unmatched"|"thread"|"coordinator") => void} [deps.onRender] 诊断回调
23
+ * @returns {() => void} disposer
24
+ */
25
+ export function registerProjectContext(deps) {
26
+ /**
27
+ * 一次请求渲染「项目上下文 + 协调器人格」。
28
+ * 三种会话都要照顾到:
29
+ * - 线程会话:注入项目上下文;
30
+ * - 协调器会话:注入项目上下文 + 人格(人格原来走 per-agent 注册,实测无效,见 runtime §11.18);
31
+ * - 其它会话:返回空串,绝不注入(全局条目必须按会话过滤,否则会污染所有会话)。
32
+ * @param {any} context
33
+ * @returns {string}
34
+ */
35
+ const render = (context) => {
36
+ try {
37
+ const store = deps.getStore();
38
+ if (!store) return "";
39
+ const sessionId = String(context?.agent?.session?.id ?? context?.session?.id ?? "");
40
+ if (sessionId === "") return "";
41
+
42
+ deps.onRender?.(sessionId, "call");
43
+ const threadProject = store.projectOfSession(sessionId);
44
+ const coordinatorProject = store
45
+ .listProjects()
46
+ .find((/** @type {any} */ item) => item.coordinatorSessionId === sessionId);
47
+ const project = threadProject ?? coordinatorProject;
48
+ if (project?.state !== "active") {
49
+ deps.onRender?.(sessionId, "unmatched");
50
+ return "";
51
+ }
52
+ deps.onRender?.(sessionId, threadProject ? "thread" : "coordinator");
53
+
54
+ const blocks = [];
55
+ if (threadProject) {
56
+ const files = readProjectFiles(deps.getDataRoot(), project.id);
57
+ const text = renderProjectContext({
58
+ project,
59
+ instructions: files.instructions,
60
+ memoryIndex: files.memoryIndex,
61
+ });
62
+ if (text !== "") blocks.push(text);
63
+ } else if (typeof deps.renderPersona === "function") {
64
+ // 协调器:项目上下文 + 人格一起给(人格里已经写明「人格不改变权限」)
65
+ const files = readProjectFiles(deps.getDataRoot(), project.id);
66
+ const text = renderProjectContext({
67
+ project,
68
+ instructions: files.instructions,
69
+ memoryIndex: files.memoryIndex,
70
+ });
71
+ if (text !== "") blocks.push(text);
72
+ const persona = deps.renderPersona(project);
73
+ if (typeof persona === "string" && persona !== "") blocks.push(persona);
74
+ }
75
+ return blocks.join("\n\n");
76
+ } catch {
77
+ // 渲染失败不应该让整个请求失败:退回空串,其它上下文照常
78
+ return "";
79
+ }
80
+ };
81
+ const dispose = deps.register({
82
+ name: "projects",
83
+ order: PROJECT_CONTEXT_ORDER,
84
+ required: false,
85
+ interpolate: false,
86
+ text: render,
87
+ });
88
+ return typeof dispose === "function" ? dispose : () => {};
89
+ }
package/lib/autofix.js ADDED
@@ -0,0 +1,111 @@
1
+ // @ts-check
2
+ // auto-fix 循环:轮数上限、无进展即停、不碰测试断言。纯函数、零 I/O。
3
+ // 依据 ADR 0003 与 m4-design.md §3:只在本地 worktree 产出提交,**不 push、不开 PR**。
4
+
5
+ /** 默认最多修几轮。 */
6
+ export const MAX_FIX_ROUNDS = 3;
7
+
8
+ /** 测试相关文件的判定(修复里碰到它们就停,防止"改测试让它绿")。 */
9
+ const TEST_FILE_PATTERNS = [
10
+ /(^|\/)test\//u,
11
+ /\.test\.[cm]?[jt]sx?$/u,
12
+ /\.spec\.[cm]?[jt]sx?$/u,
13
+ /(^|\/)__tests__\//u,
14
+ /(^|\/)tests?\//u,
15
+ /(^|\/)testdata\//u,
16
+ /(^|\/)fixtures?\//u,
17
+ ];
18
+
19
+ /**
20
+ * 把 CI 日志压成稳定的"错误签名",用来判断「是不是同一个错」。
21
+ * 去掉时间戳、行号、耗时、随机 id,避免同一错误因噪声被判成新错误。
22
+ * @param {string} logText
23
+ * @param {number} [maxLines]
24
+ * @returns {string}
25
+ */
26
+ export function errorSignature(logText, maxLines = 8) {
27
+ const lines = String(logText ?? "")
28
+ .split("\n")
29
+ .map((line) =>
30
+ line
31
+ .replace(/\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)?Z?/gu, "<ts>")
32
+ .replace(/\b\d+(\.\d+)?\s?(ms|s|m)\b/gu, "<dur>")
33
+ .replace(/:\d+:\d+/gu, ":<loc>")
34
+ .replace(/\b[0-9a-f]{7,40}\b/gu, "<sha>")
35
+ .replace(/\s+/gu, " ")
36
+ .trim(),
37
+ )
38
+ .filter((line) => /error|fail|expected|received|cannot|not found|undefined/iu.test(line));
39
+ const picked = lines.slice(0, maxLines);
40
+ return picked.join("\n").slice(0, 1200);
41
+ }
42
+
43
+ /**
44
+ * 修复是否碰到了测试文件。
45
+ * @param {string[]} changedFiles
46
+ * @returns {string[]} 命中的文件
47
+ */
48
+ export function touchedTestFiles(changedFiles) {
49
+ const files = Array.isArray(changedFiles) ? changedFiles : [];
50
+ return files.filter((file) => TEST_FILE_PATTERNS.some((pattern) => pattern.test(String(file))));
51
+ }
52
+
53
+ /**
54
+ * 判断还要不要继续修。
55
+ * @param {object} input
56
+ * @param {number} input.round 已经修了几轮
57
+ * @param {number} [input.maxRounds]
58
+ * @param {string[]} [input.changedFiles] 上一轮的改动文件(用于"无进展"与"碰测试"判断)
59
+ * @param {string} [input.previousSignature]
60
+ * @param {string} [input.currentSignature]
61
+ * @param {boolean} [input.sameSignatureTwice]
62
+ * @returns {{ continue: boolean, reason: string }}
63
+ */
64
+ export function shouldContinueFix(input) {
65
+ const round = Number.isFinite(input?.round) ? Number(input.round) : 0;
66
+ const maxRounds = Number.isFinite(input?.maxRounds) ? Number(input.maxRounds) : MAX_FIX_ROUNDS;
67
+
68
+ if (round >= maxRounds) return { continue: false, reason: "max-rounds" };
69
+
70
+ const changed = Array.isArray(input?.changedFiles) ? input.changedFiles : [];
71
+
72
+ // 顺序有讲究:同样是「该停」,但要给出**最可操作**的原因。
73
+ // 「同一个错还在」比「没有改动」更能说明问题,所以先判它。
74
+ const tests = touchedTestFiles(changed);
75
+ if (tests.length > 0) return { continue: false, reason: "test-touched" };
76
+
77
+ if (input?.sameSignatureTwice === true) return { continue: false, reason: "same-error-twice" };
78
+
79
+ const previous = String(input?.previousSignature ?? "");
80
+ const current = String(input?.currentSignature ?? "");
81
+ if (round > 0 && previous !== "" && current !== "" && previous === current) {
82
+ return { continue: false, reason: "same-error-twice" };
83
+ }
84
+
85
+ if (round > 0 && changed.length === 0) return { continue: false, reason: "no-progress" };
86
+
87
+ return { continue: true, reason: "" };
88
+ }
89
+
90
+ /**
91
+ * 生成下一轮修复任务的提示词(明确禁区,避免模型自作主张)。
92
+ * @param {{ round: number, signature: string, projectName?: string }} input
93
+ * @returns {string}
94
+ */
95
+ export function buildFixTask(input) {
96
+ const round = Number.isFinite(input?.round) ? Number(input.round) + 1 : 1;
97
+ const signature = String(input?.signature ?? "").trim();
98
+ return [
99
+ `修复 CI 失败(第 ${round} 轮)。`,
100
+ "",
101
+ "错误摘要:",
102
+ "```",
103
+ signature === "" ? "(没抓到明确的错误行,先自己复现)" : signature,
104
+ "```",
105
+ "",
106
+ "约束(必须遵守):",
107
+ "- 只改产品代码,**不要修改测试文件或断言**;如果修复必须先改测试,停下来说明原因。",
108
+ "- 不要 push、不要开 PR、不要改版本号。",
109
+ "- 改完在本地提交一次,提交信息写清修的是什么。",
110
+ ].join("\n");
111
+ }
package/lib/autopr.js ADDED
@@ -0,0 +1,115 @@
1
+ // @ts-check
2
+ // auto PR:档位决策与幂等。纯函数、零 I/O。
3
+ // 依据 m4-design.md §2:四档默认关;同一线程只开一次 PR;失败降级不重试到天荒地老。
4
+
5
+ /** 四档(默认 off)。 */
6
+ export const PR_TIERS = Object.freeze(["off", "draft", "ready", "auto-merge"]);
7
+
8
+ /** 失败最多重试次数(超过就停在人手里)。 */
9
+ export const MAX_PR_ATTEMPTS = 2;
10
+
11
+ /**
12
+ * 线程进入 done 之后,下一步对 PR 做什么。
13
+ * @param {object} input
14
+ * @param {string} [input.tier]
15
+ * @param {{ branch?: string|null, prNumber?: number|null, commits?: number, attempts?: number, ciState?: string }} input.thread
16
+ * @returns {{ action: "none"|"open-draft"|"open-ready"|"update"|"merge"|"wait-ci"|"give-up", reason: string }}
17
+ */
18
+ export function nextPrAction(input) {
19
+ const tier = PR_TIERS.includes(String(input?.tier ?? "")) ? String(input.tier) : "off";
20
+ const thread = input?.thread ?? {};
21
+ const branch = typeof thread.branch === "string" ? thread.branch : "";
22
+ const attempts = Number.isFinite(thread.attempts) ? Number(thread.attempts) : 0;
23
+ const hasPr = Number.isInteger(thread.prNumber) && Number(thread.prNumber) > 0;
24
+
25
+ if (tier === "off") return { action: "none", reason: "tier-off" };
26
+ if (branch === "") return { action: "none", reason: "no-branch" };
27
+ if (!/^dsh\//u.test(branch)) return { action: "none", reason: "branch-not-ours" };
28
+ if (attempts >= MAX_PR_ATTEMPTS) return { action: "give-up", reason: "too-many-attempts" };
29
+
30
+ const commits = Number.isFinite(thread.commits) ? Number(thread.commits) : 0;
31
+ if (!hasPr && commits <= 0) return { action: "none", reason: "no-commits" };
32
+
33
+ if (tier === "auto-merge") {
34
+ if (!hasPr) return { action: "open-ready", reason: "auto-merge-first-open" };
35
+ const ci = String(thread.ciState ?? "");
36
+ if (ci === "passing") return { action: "merge", reason: "ci-passing" };
37
+ if (ci === "failing") return { action: "give-up", reason: "ci-failing" };
38
+ return { action: "wait-ci", reason: "ci-pending" };
39
+ }
40
+
41
+ if (hasPr) return { action: "update", reason: "pr-exists" };
42
+ if (tier === "draft") return { action: "open-draft", reason: "tier-draft" };
43
+ return { action: "open-ready", reason: "tier-ready" };
44
+ }
45
+
46
+ /**
47
+ * 生成 PR 标题与正文骨架(正文里必须写明"这是自动开的",以及恢复方式)。
48
+ * @param {{ projectName?: string, task?: string, sessionId?: string, branch?: string }} input
49
+ * @returns {{ title: string, body: string }}
50
+ */
51
+ export function buildPrText(input) {
52
+ const task = String(input?.task ?? "").trim() || "project thread";
53
+ const firstLine = task.split("\n")[0].slice(0, 80);
54
+ const projectName = String(input?.projectName ?? "").trim() || "project";
55
+ const sessionId = String(input?.sessionId ?? "");
56
+ const body = [
57
+ `Automated by the **projects** plugin (project: ${projectName}).`,
58
+ "",
59
+ "**Task**",
60
+ task.length > 800 ? `${task.slice(0, 800)}\n…(truncated)` : task,
61
+ "",
62
+ "**How to undo**",
63
+ "- Close this PR without merging; the branch and worktree are kept until you archive the thread.",
64
+ "- Nothing is merged automatically unless the project's `auto-merge` tier and the `merge` danger switch are both on.",
65
+ "",
66
+ `<sub>thread: ${sessionId}</sub>`,
67
+ ].join("\n");
68
+ return { title: `dsh: ${firstLine}`, body };
69
+ }
70
+
71
+ /**
72
+ * 是否允许合并(auto-merge 档的额外门槛;真正执行仍要过执行器闸门)。
73
+ * @param {{ tier?: string, ciState?: string, mergeable?: boolean, dangerMerge?: boolean }} input
74
+ * @returns {{ ok: boolean, reason: string }}
75
+ */
76
+ export function canAutoMerge(input) {
77
+ if (String(input?.tier ?? "") !== "auto-merge")
78
+ return { ok: false, reason: "tier-not-auto-merge" };
79
+ if (input?.dangerMerge !== true) return { ok: false, reason: "switch-off" };
80
+ if (String(input?.ciState ?? "") !== "passing") return { ok: false, reason: "ci-not-passing" };
81
+ if (input?.mergeable === false) return { ok: false, reason: "not-mergeable" };
82
+ return { ok: true, reason: "" };
83
+ }
84
+
85
+ /**
86
+ * 生成 `gh pr create` 的 argv(不做 shell 插值)。
87
+ * @param {{ title: string, body: string, base?: string, draft?: boolean, branch: string, repo?: string }} input
88
+ * @returns {{ argv: string[] } | { error: string }}
89
+ */
90
+ export function planPrCreate(input) {
91
+ const title = String(input?.title ?? "").trim();
92
+ const body = String(input?.body ?? "").trim();
93
+ const branch = String(input?.branch ?? "").trim();
94
+ if (title === "") return { error: "title-required" };
95
+ if (body === "") return { error: "body-required" };
96
+ if (!/^dsh\/[A-Za-z0-9._/-]+$/u.test(branch)) return { error: "branch-not-ours" };
97
+
98
+ const argv = ["pr", "create", "--head", branch, "--title", title, "--body", body];
99
+ if (typeof input?.base === "string" && input.base !== "") argv.push("--base", input.base);
100
+ if (typeof input?.repo === "string" && input.repo !== "") argv.push("--repo", input.repo);
101
+ if (input?.draft === true) argv.push("--draft");
102
+ return { argv };
103
+ }
104
+
105
+ /**
106
+ * 从 `gh pr create` 的输出里取出 PR 号(输出形如 https://github.com/o/r/pull/123)。
107
+ * @param {string} stdout
108
+ * @returns {number|null}
109
+ */
110
+ export function parsePrNumber(stdout) {
111
+ const match = String(stdout ?? "").match(/\/pull\/(\d+)/u);
112
+ if (!match) return null;
113
+ const value = Number(match[1]);
114
+ return Number.isInteger(value) && value > 0 ? value : null;
115
+ }
package/lib/budget.js ADDED
@@ -0,0 +1,95 @@
1
+ // @ts-check
2
+ // 项目预算闸:纯函数、零 I/O。
3
+ // M2 范围只做「线程数量」维度(每日新建数 + 并发数);
4
+ // token 维度的花费闸留到 M3 与 tokenMeter 一起接(避免现在猜计量口径)。
5
+
6
+ /** 一天的毫秒数。 */
7
+ export const DAY_MS = 24 * 60 * 60 * 1000;
8
+
9
+ /**
10
+ * 一条线程记录是否算在「今天」。
11
+ * @param {{ createdAt?: string }} thread
12
+ * @param {number} now
13
+ * @returns {boolean}
14
+ */
15
+ export function isToday(thread, now) {
16
+ const created = Date.parse(String(thread?.createdAt ?? ""));
17
+ if (!Number.isFinite(created)) return false;
18
+ return created >= startOfDay(now) && created < startOfDay(now) + DAY_MS;
19
+ }
20
+
21
+ /**
22
+ * 本地时区的一天起点。
23
+ * @param {number} now
24
+ * @returns {number}
25
+ */
26
+ export function startOfDay(now) {
27
+ const date = new Date(now);
28
+ date.setHours(0, 0, 0, 0);
29
+ return date.getTime();
30
+ }
31
+
32
+ /**
33
+ * 是否允许再建一个线程。
34
+ * 规则:项目暂停 → 拒;每日上限 → 拒;并发上限 → 拒。任一命中给可读原因。
35
+ * @param {object} input
36
+ * @param {{state?: string, budget?: {maxThreadsPerDay?: number|null, maxConcurrent?: number|null}}} input.project
37
+ * @param {{createdAt?: string, state?: string}[]} input.threads
38
+ * @param {number} [input.now]
39
+ * @returns {{ ok: boolean, reason: string, used: { today: number, running: number } }}
40
+ */
41
+ export function checkThreadBudget(input) {
42
+ const now = Number.isFinite(input?.now) ? Number(input.now) : Date.now();
43
+ const threads = Array.isArray(input?.threads) ? input.threads : [];
44
+ const today = threads.filter((thread) => isToday(thread, now)).length;
45
+ const running = threads.filter((thread) => thread?.state === "working").length;
46
+ const used = { today, running };
47
+
48
+ if (input?.project?.state === "paused") return { ok: false, reason: "project-paused", used };
49
+ if (input?.project?.state === "archived") return { ok: false, reason: "project-archived", used };
50
+
51
+ const maxPerDay = input?.project?.budget?.maxThreadsPerDay;
52
+ if (Number.isFinite(maxPerDay) && today >= Number(maxPerDay)) {
53
+ return { ok: false, reason: "budget/threads-per-day", used };
54
+ }
55
+
56
+ const maxConcurrent = input?.project?.budget?.maxConcurrent;
57
+ if (Number.isFinite(maxConcurrent) && running >= Number(maxConcurrent)) {
58
+ return { ok: false, reason: "budget/concurrent-threads", used };
59
+ }
60
+
61
+ return { ok: true, reason: "", used };
62
+ }
63
+
64
+ /**
65
+ * 与「今天」相关的 token 累计(宿主的 `TokenUsage` 形状:inputTokens/outputTokens/totalTokens?)。
66
+ * @param {{ usage?: any, at?: string }} record
67
+ * @param {number} now
68
+ * @returns {number}
69
+ */
70
+ export function tokensOf(record, now) {
71
+ if (!isToday({ createdAt: record?.at }, now)) return 0;
72
+ const usage = record?.usage;
73
+ if (!usage || typeof usage !== "object") return 0;
74
+ const total = Number(usage.totalTokens);
75
+ if (Number.isFinite(total) && total >= 0) return total;
76
+ const input = Number(usage.inputTokens);
77
+ const output = Number(usage.outputTokens);
78
+ const sum = (Number.isFinite(input) ? input : 0) + (Number.isFinite(output) ? output : 0);
79
+ return Math.max(0, sum);
80
+ }
81
+
82
+ /**
83
+ * 今天的 token 花费是否已到线。
84
+ * 单独的判定(不与线程数混在一起)——两件事的处置不同:到 token 线应该「暂停项目」,
85
+ * 到线程数线只是「今天不再建」。
86
+ * @param {{ dailyTokens?: number|null, usedTokens: number }} input
87
+ * @returns {{ ok: boolean, used: number, limit: number|null, reason: string }}
88
+ */
89
+ export function checkTokenBudget(input) {
90
+ const limit = Number.isFinite(input?.dailyTokens) ? Number(input.dailyTokens) : null;
91
+ const used = Number.isFinite(input?.usedTokens) ? Number(input.usedTokens) : 0;
92
+ if (limit === null) return { ok: true, used, limit: null, reason: "" };
93
+ if (used >= limit) return { ok: false, used, limit, reason: "budget/daily-tokens" };
94
+ return { ok: true, used, limit, reason: "" };
95
+ }