dsh-plan-files 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,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DSH Plan Files contributors
4
+ Copyright (c) 2026 DSH Claude Code Memory Reader contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # Plan Files for DeepSeek Harness
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
+ [中文说明](README.zh-CN.md)
4
+
5
+ DSH Plan Files keeps DeepSeek Harness (DSH) plans in independent Markdown files while using DSH's native Plan Review for feedback and approval.
6
+
7
+ The plugin supports DSH `0.2.2-rc.3` and Node.js 22 or later.
8
+
9
+ ## Installation
10
+
11
+ ### Local source
12
+
13
+ Clone this repository and install its root directory into the DSH profile you use. This example uses the native `tui` profile.
14
+
15
+ ```bash
16
+ git clone https://github.com/paigeman/dsh-plan-files.git
17
+ cd dsh-plan-files
18
+ dsh plugin --profile tui add "link:$PWD"
19
+ dsh --profile tui --dump-config
20
+ ```
21
+
22
+ Check for component ID `plan-files` and package name `dsh-plan-files` in the configuration. Keep the source directory after installing a local link.
23
+
24
+ In DSH Desktop, open **Plugins**, choose **Add plugin**, select a local directory, and enter the repository's absolute path. Enable the bundle and its **Plan Files** component.
25
+
26
+ ### npm package
27
+
28
+ Install the published package into your profile.
29
+
30
+ ```bash
31
+ dsh plugin --profile tui add dsh-plan-files
32
+ ```
33
+
34
+ In Desktop's plugin manager, choose the npm registry source and enter `dsh-plan-files`.
35
+
36
+ ## Workflow
37
+
38
+ ```text
39
+ /plan
40
+ → Create and save a Markdown plan
41
+ → Open native Plan Review
42
+ → Receive natural-language feedback
43
+ → Apply localized edits to the same file
44
+ → Open native Plan Review again
45
+ → Approve, exit Plan Mode, and keep the file
46
+ ```
47
+
48
+ Give feedback in ordinary language. The Agent locates the relevant passages and applies exact replacements or localized patches to the same file. Text outside a patch is preserved verbatim. Ambiguous feedback or a significantly broader change calls for clarification.
49
+
50
+ The plugin retains the native `/plan`, `exit_plan_mode`, **Approve**, **Keep planning**, and feedback flow.
51
+
52
+ ## Plan files
53
+
54
+ Plans live in `~/.dsh/plans/`, with names following this pattern. A configured `DSH_HOME` changes the base directory.
55
+
56
+ ```text
57
+ ~/.dsh/plans/YYYY-MM-DD-task-summary-short-id.md
58
+ ```
59
+
60
+ The `plan_file` tool creates the initial file and provides `read` and `edit` actions for revisions. An edit supplies the version from the last read and literal `old_text`/`new_text` replacements. The Agent handles these arguments while you give ordinary feedback.
61
+
62
+ Each session has one plan file. Feedback, session resume, and leaving and re-entering Plan Mode all reuse that file. A fork copies the latest plan content recorded in its inherited history into an independent file for the new session. Small association records live under the plans directory's `.state/` subdirectory. File creation records its identity before publishing the Markdown so an interrupted first write can retry the same path.
63
+
64
+ ## Editing and approval checks
65
+
66
+ Exact edits preserve text outside their matches, including line endings, a UTF-8 BOM, and the presence or absence of a final newline. Ambiguous matches, overlapping edits, stale versions, and whole-file replacements are rejected. Native filesystem writes to the managed directory are directed to `plan_file`, including nested tool dispatches.
67
+
68
+ The plugin compares native `exit_plan_mode` input with the saved file and checks the file again before opening review and before returning approval to the native tool. Reads, searches, temporary-directory operations, and other tools retain DSH's existing permissions.
69
+
70
+ Shell and other independent processes run under their existing DSH permissions. A process with write access to the plans directory can bypass file-tool restrictions. Version checks detect observed external changes. DSH's filesystem backend still has a check-to-publication race with non-cooperating external writers.
71
+
72
+ ## Compatibility
73
+
74
+ | Plugin version | Supported DSH versions |
75
+ | --------------------- | ---------------------- |
76
+ | 0.1.0 | 0.2.2-rc.3 |
77
+ | 0.1.1 (this checkout) | 0.2.2-rc.3 |
78
+
79
+ The supported DSH version matches `engines.dsh` and the pinned test workspace. GitHub Actions is configured to run native compatibility tests and packed-plugin checks on Linux, macOS, and Windows. Local macOS validation covers the native DSH runtime and real-model Desktop sessions using the standard and PTC presets. Compatibility with dsh-TUI `0.20.1` has also been tested through its `/plan` picker and Shift+Tab read-only mode. Linux sandbox behavior remains unverified.
80
+
81
+ ## Contributing
82
+
83
+ Development setup, formatting rules, lint commands, and CI checks are documented in [CONTRIBUTING.md](CONTRIBUTING.md).
84
+
85
+ Version tags trigger package verification, GitHub Release creation, and npm publication when its publishing configuration is enabled. Release previews and account setup are covered in the [release instructions](CONTRIBUTING.md#releases).
86
+
87
+ MIT licensed.
@@ -0,0 +1,87 @@
1
+ # Plan Files for DeepSeek Harness
2
+
3
+ [English guide](README.md)
4
+
5
+ DSH Plan Files 为 DeepSeek Harness(DSH)保存独立的 Markdown 计划文件,并沿用 DSH 原生 Plan Review 完成反馈和审批。
6
+
7
+ 插件支持 DSH `0.2.2-rc.3`,需要 Node.js 22 或以上版本。
8
+
9
+ ## 安装
10
+
11
+ ### 本地源码
12
+
13
+ 克隆仓库后,将仓库根目录安装到所用的 DSH profile。下面以原生 `tui` profile 为例。
14
+
15
+ ```bash
16
+ git clone https://github.com/paigeman/dsh-plan-files.git
17
+ cd dsh-plan-files
18
+ dsh plugin --profile tui add "link:$PWD"
19
+ dsh --profile tui --dump-config
20
+ ```
21
+
22
+ 在输出中检查组件 ID `plan-files` 和包名 `dsh-plan-files`。本地安装会引用源码目录,需要保留该目录。
23
+
24
+ 使用 DSH Desktop 时,打开 **插件**,选择 **添加插件**,安装来源选本地目录,填入仓库的绝对路径。安装后启用 bundle 及 **计划文件** 组件。
25
+
26
+ ### npm 包
27
+
28
+ 可以直接按包名安装到所用 profile。
29
+
30
+ ```bash
31
+ dsh plugin --profile tui add dsh-plan-files
32
+ ```
33
+
34
+ Desktop 的插件管理器中选择 npm registry 来源,输入 `dsh-plan-files` 即可。
35
+
36
+ ## 使用流程
37
+
38
+ ```text
39
+ /plan
40
+ → 创建并保存 Markdown 计划文件
41
+ → 打开原生 Plan Review
42
+ → 用户提供自然语言修改意见
43
+ → Agent 局部编辑同一文件
44
+ → 再次打开原生 Plan Review
45
+ → 批准后退出 Plan Mode,并保留文件
46
+ ```
47
+
48
+ 用户照常用自然语言反馈,Agent 自行定位相关段落,通过精确替换或局部补丁修订同一文件。补丁外文本原样保留。意见存在歧义,或修改范围需要明显扩大时,再澄清。
49
+
50
+ 插件沿用原生 `/plan`、`exit_plan_mode`、**Approve**、**Keep planning** 和反馈流程。
51
+
52
+ ## 计划文件
53
+
54
+ 计划文件的默认目录为 `~/.dsh/plans/`,配置 `DSH_HOME` 时会使用对应目录。文件名采用以下形式。
55
+
56
+ ```text
57
+ ~/.dsh/plans/YYYY-MM-DD-任务摘要-短ID.md
58
+ ```
59
+
60
+ `plan_file` 工具负责首次创建,并提供 `read` 和 `edit` 动作。修改时提交上次读取的文件版本及精确的 `old_text`、`new_text` 替换。工具参数由 Agent 处理,用户照常用自然语言反馈。
61
+
62
+ 每个会话关联一个计划文件。反馈、恢复会话,以及退出后再次进入 Plan Mode,都会继续使用这个文件。Fork 会根据继承历史中最后记录的计划内容,为新会话创建独立副本。计划目录下的 `.state/` 保存简要关联记录。首次创建先记录文件身份,再发布 Markdown,写入中断后可以重试同一路径。
63
+
64
+ ## 编辑与审批检查
65
+
66
+ 精确编辑保留匹配范围外的文本,包括换行格式、UTF-8 BOM 和文件末尾是否换行。匹配不唯一、编辑重叠、版本过期和全文替换会被拒绝。原生文件工具对计划目录的写入会被引导到 `plan_file`,嵌套工具调用也经过这些检查。
67
+
68
+ 插件核对 `exit_plan_mode` 参数与已保存文件,在打开审批及将批准答案交还原生工具前再次检查文件。读取、搜索、临时目录操作和其他工具沿用 DSH 现有权限。
69
+
70
+ Shell 和其他独立进程仍使用 DSH 既有权限。拥有计划目录写权限的进程可以绕过文件工具限制,版本检查会检测已经观察到的外部改动。对于非协作的外部写入,DSH 文件后端在版本检查到文件发布之间仍有竞态窗口。
71
+
72
+ ## 兼容性
73
+
74
+ | 插件版本 | 支持的 DSH 版本 |
75
+ | ----------------- | --------------- |
76
+ | 0.1.0 | 0.2.2-rc.3 |
77
+ | 0.1.1(当前源码) | 0.2.2-rc.3 |
78
+
79
+ 支持的 DSH 版本与 `engines.dsh` 及固定版本的测试 workspace 一致。GitHub Actions 已配置 Linux、macOS、Windows 的原生兼容性测试和打包验证。本地已在 macOS 验证 DSH 原生运行时及 Desktop 真实模型会话,覆盖标准预设和 PTC 预设。另已验证 dsh-TUI `0.20.1` 的兼容性,包括 `/plan` 选择器和 Shift+Tab 只读模式。Linux 沙箱行为尚未验证。
80
+
81
+ ## 参与开发
82
+
83
+ 开发环境、格式化规则、lint 命令和 CI 检查见 [CONTRIBUTING.md](CONTRIBUTING.md)。
84
+
85
+ 版本标签会触发打包验证、GitHub Release 创建,并在 npm 发布配置启用后执行发包。发布预演和账号配置见[发布说明](CONTRIBUTING.md#releases)。
86
+
87
+ 本项目采用 MIT 许可。
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: plan-files
3
+ name: "dsh-plan-files"
package/index.js ADDED
@@ -0,0 +1,216 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { PlanStore, planning } from "./lib/plan-store.js";
4
+
5
+ export const name = "plan-files";
6
+ export const inject = ["fs", "tools", "systemPrompt"];
7
+
8
+ const parameters = {
9
+ type: "object",
10
+ additionalProperties: false,
11
+ required: ["action"],
12
+ properties: {
13
+ action: { type: "string", enum: ["create", "read", "edit"] },
14
+ title: { type: "string", description: "Short task summary used only when creating the plan." },
15
+ content: {
16
+ type: "string",
17
+ description: "Complete initial Markdown, accepted only for create.",
18
+ },
19
+ version: {
20
+ type: "string",
21
+ description: "Exact version returned by the most recent plan_file call, required for edit.",
22
+ },
23
+ edits: {
24
+ type: "array",
25
+ description:
26
+ "Localized literal replacements against the current file. Each old_text must match once.",
27
+ items: {
28
+ type: "object",
29
+ additionalProperties: false,
30
+ required: ["old_text", "new_text"],
31
+ properties: {
32
+ old_text: { type: "string" },
33
+ new_text: { type: "string" },
34
+ },
35
+ },
36
+ },
37
+ },
38
+ };
39
+
40
+ export async function apply(ctx, config = {}) {
41
+ const directory =
42
+ config.plansDir ?? join(process.env.DSH_HOME || join(homedir(), ".dsh"), "plans");
43
+ const stores = new WeakMap();
44
+ const storeFor = (agent) => {
45
+ if (!agent) throw new Error("A planning session is required.");
46
+ if (!stores.has(agent.session)) stores.set(agent.session, new PlanStore(ctx, directory));
47
+ return stores.get(agent.session);
48
+ };
49
+ const reviews = new Map();
50
+ const denials = new Map();
51
+ let disposed = false;
52
+ ctx.effect(() => () => {
53
+ disposed = true;
54
+ });
55
+
56
+ ctx.tools.register(
57
+ {
58
+ name: "plan_file",
59
+ description:
60
+ "Read, create, or precisely edit this session's Markdown plan. Read first on entering Plan Mode. Create only if this session has no plan. Reuse the same file after feedback, resume, and Plan Mode re-entry. Submit its exact content through native exit_plan_mode.",
61
+ parameters,
62
+ output: {
63
+ schema: {
64
+ type: "object",
65
+ additionalProperties: false,
66
+ required: ["protocol", "episode", "path", "version", "content"],
67
+ properties: Object.fromEntries(
68
+ ["protocol", "episode", "path", "version", "content"].map((key) => [
69
+ key,
70
+ { type: "string" },
71
+ ]),
72
+ ),
73
+ },
74
+ render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }],
75
+ },
76
+ execute: (args, exec) => storeFor(exec.agent).tool(args, exec),
77
+ },
78
+ { when: ({ agent }) => planning(agent) },
79
+ );
80
+
81
+ ctx.systemPrompt.section({
82
+ name: "plan-files:workflow",
83
+ order: 910,
84
+ text: ({ agent }) =>
85
+ !planning(agent)
86
+ ? ""
87
+ : [
88
+ "Use plan_file to keep one Markdown plan file for this session across Plan Mode entries.",
89
+ "Saving and editing that plan through plan_file is permitted in Plan Mode. Keep implementation changes for approved execution.",
90
+ "Read the session's existing plan when entering Plan Mode. Create an initial plan only when this session has none, before its first review. After approval and re-entry, continue reading and locally editing the same file.",
91
+ "For feedback and later planning requests, use exact localized edits on that file, preserving unrelated content.",
92
+ "The user gives ordinary natural-language feedback. Locate the relevant passages yourself. Clarify ambiguous feedback or a significantly expanded scope.",
93
+ "Supply the version returned by plan_file when editing. Native write, edit, and apply_patch cannot modify managed plans.",
94
+ "Call native exit_plan_mode with the exact saved content. Use native Approve, Keep planning, and feedback normally.",
95
+ "Other tools retain their existing DSH permissions.",
96
+ ].join("\n"),
97
+ });
98
+
99
+ ctx.on("tools/pre-execute", async (exec, next) => {
100
+ const args = exec.arguments ?? {};
101
+ const paths = [];
102
+ if (
103
+ ["write", "edit"].includes(exec.name) ||
104
+ (exec.name === "str_replace_editor" && args.command !== "view")
105
+ )
106
+ paths.push(args.file_path ?? args.path);
107
+ if (exec.name === "apply_patch" && typeof args.input === "string") {
108
+ for (const match of args.input.matchAll(
109
+ /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm,
110
+ ))
111
+ paths.push(match[1]);
112
+ }
113
+ if (paths.length === 0) return next();
114
+ const fs = ctx.fs;
115
+ if (!fs) return next();
116
+ const root = await fs.resolve(directory, { signal: exec.signal });
117
+ for (const path of paths.filter((path) => typeof path === "string")) {
118
+ const target = await fs.resolve(path, {
119
+ cwd: exec.agent?.session.header.cwd,
120
+ signal: exec.signal,
121
+ });
122
+ if (fs.contains(root, target))
123
+ denials.set(
124
+ exec.token,
125
+ "Use plan_file for managed plans so edits preserve all text outside the exact replacements.",
126
+ );
127
+ }
128
+ return next();
129
+ });
130
+ ctx.tools.guard((exec) => denials.get(exec.token));
131
+ ctx.on("tools/result", (exec) => {
132
+ denials.delete(exec.token);
133
+ });
134
+
135
+ for (const event of ["fs/write-intent", "fs/edit-intent", "fs/delete-intent"]) {
136
+ ctx.on(
137
+ event,
138
+ async (target, actor, next) => {
139
+ const fs = ctx.fs;
140
+ if (!fs) return next();
141
+ const root = await fs.resolve(directory);
142
+ if (fs.contains(root, target)) throw new Error("Use plan_file to modify managed plans.");
143
+ return next();
144
+ },
145
+ { prepend: true },
146
+ );
147
+ }
148
+
149
+ ctx.on("tools/execute", async (exec, next) => {
150
+ if (
151
+ exec.name !== "exit_plan_mode" ||
152
+ !exec.agent ||
153
+ exec.agent.session.header.origin === "subagent"
154
+ )
155
+ return next();
156
+ const store = storeFor(exec.agent);
157
+ return store.exclusive(exec.agent.session.id, async () => {
158
+ const current = await store.current(exec.agent, exec.signal);
159
+ const snapshot = await store.snapshot(current.path, exec.signal);
160
+ if (exec.arguments.plan !== snapshot.content) {
161
+ throw new Error(
162
+ "Review content differs from the saved plan. Read plan_file and submit its exact content.",
163
+ );
164
+ }
165
+ const key = `${exec.agent.session.id}/${exec.callId}`;
166
+ reviews.set(key, { store, path: current.path, ...snapshot });
167
+ try {
168
+ return await next();
169
+ } finally {
170
+ reviews.delete(key);
171
+ }
172
+ });
173
+ });
174
+
175
+ ctx.on(
176
+ "user-questions/request",
177
+ async (request, next) => {
178
+ const checks = request.questions
179
+ .filter((question) => question.intent?.kind === "plan-review")
180
+ .flatMap((question) => {
181
+ const key = `${request.agent?.session.id}/${question.intent.callId}`;
182
+ const review = reviews.get(key);
183
+ if (!review) return [];
184
+ if (question.detail !== review.content)
185
+ throw new Error("Plan review differs from the saved-file submission.");
186
+ return [{ question, review }];
187
+ });
188
+ for (const { review } of checks) {
189
+ const current = await review.store.snapshot(review.path, request.signal);
190
+ if (current.version !== review.version || current.content !== review.content) {
191
+ throw new Error(
192
+ "The plan changed before review opened. Submit the current saved file again.",
193
+ );
194
+ }
195
+ }
196
+ const answer = await next();
197
+ for (const { question, review } of checks) {
198
+ const item = answer.answers.find((item) => item.id === question.id);
199
+ if (
200
+ item?.selected.length !== 1 ||
201
+ item.selected[0] !== question.intent.approve ||
202
+ item.custom !== undefined
203
+ )
204
+ continue;
205
+ const current = await review.store.snapshot(review.path, request.signal);
206
+ if (disposed || current.version !== review.version || current.content !== review.content) {
207
+ throw new Error(
208
+ "The plan changed during review. Present the current saved file again before approval.",
209
+ );
210
+ }
211
+ }
212
+ return answer;
213
+ },
214
+ { prepend: true },
215
+ );
216
+ }
@@ -0,0 +1,35 @@
1
+ export function validateText(text) {
2
+ if (typeof text !== "string" || text.includes("\0") || Buffer.from(text).toString() !== text) {
3
+ throw new Error("Plan text must be valid UTF-8 without NUL characters.");
4
+ }
5
+ }
6
+
7
+ export function applyExactEdits(content, edits) {
8
+ if (!Array.isArray(edits) || edits.length === 0) {
9
+ throw new Error("Supply at least one exact old_text/new_text edit.");
10
+ }
11
+ const replacements = edits.map(({ old_text: oldText, new_text: newText }) => {
12
+ validateText(oldText);
13
+ validateText(newText);
14
+ if (oldText.length === 0) throw new Error("old_text must be nonempty.");
15
+ const start = content.indexOf(oldText);
16
+ if (start < 0 || content.indexOf(oldText, start + 1) >= 0) {
17
+ throw new Error("old_text must match exactly once. Read the plan and include more context.");
18
+ }
19
+ return { start, end: start + oldText.length, text: newText };
20
+ });
21
+ replacements.sort((a, b) => a.start - b.start);
22
+ let cursor = 0;
23
+ let matched = 0;
24
+ let result = "";
25
+ for (const replacement of replacements) {
26
+ if (replacement.start < cursor) throw new Error("Plan edits must not overlap.");
27
+ result += content.slice(cursor, replacement.start) + replacement.text;
28
+ matched += replacement.end - replacement.start;
29
+ cursor = replacement.end;
30
+ }
31
+ if (matched === content.length) {
32
+ throw new Error("Full-plan replacement is disabled. Use localized edits to the existing plan.");
33
+ }
34
+ return result + content.slice(cursor);
35
+ }
@@ -0,0 +1,249 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { basename, isAbsolute, join } from "node:path";
3
+ import { applyExactEdits, validateText } from "./exact-edit.js";
4
+
5
+ const MAX_BYTES = 4 * 1024 * 1024;
6
+ export const PROTOCOL = "dsh-plan-files/1";
7
+
8
+ export function planEpisode(session) {
9
+ let episode;
10
+ for (const event of session.snapshotEvents()) {
11
+ if (event.type === "plan/mode" && event.data.active) episode = event.seq;
12
+ }
13
+ if (episode === undefined) throw new Error("Enter native Plan Mode with /plan first.");
14
+ return String(episode);
15
+ }
16
+
17
+ export function planning(agent) {
18
+ if (!agent || agent.session.header.origin === "subagent") return false;
19
+ let active = false;
20
+ for (const event of agent.session.snapshotEvents()) {
21
+ if (event.type === "plan/mode") active = event.data.active;
22
+ }
23
+ return active;
24
+ }
25
+
26
+ function slug(title) {
27
+ const summary = title
28
+ .normalize("NFKC")
29
+ .replace(/[^\p{L}\p{N}]+/gu, "-")
30
+ .replace(/^-|-$/g, "");
31
+ return Array.from(summary).slice(0, 48).join("") || "plan";
32
+ }
33
+
34
+ export class PlanStore {
35
+ constructor(ctx, directory) {
36
+ if (!isAbsolute(directory)) throw new Error("plansDir must be an absolute path.");
37
+ this.ctx = ctx;
38
+ this.directory = directory;
39
+ this.locks = new Map();
40
+ }
41
+
42
+ async exclusive(key, operation) {
43
+ const previous = this.locks.get(key) ?? Promise.resolve();
44
+ const current = previous.catch(() => {}).then(operation);
45
+ this.locks.set(key, current);
46
+ try {
47
+ return await current;
48
+ } finally {
49
+ if (this.locks.get(key) === current) this.locks.delete(key);
50
+ }
51
+ }
52
+
53
+ async target(path, signal) {
54
+ const fs = this.ctx.fs;
55
+ for (const checked of [this.directory, join(this.directory, ".state"), path]) {
56
+ if ((await fs.lstat(checked, undefined, signal))?.type === "symlink") {
57
+ throw new Error("Managed plan paths must not be symbolic links.");
58
+ }
59
+ }
60
+ const root = await fs.resolve(this.directory, { signal });
61
+ const target = await fs.resolve(path, { signal });
62
+ if (!fs.contains(root, target)) throw new Error("Plan path escapes plansDir.");
63
+ return target;
64
+ }
65
+
66
+ async snapshot(path, signal, optional = false) {
67
+ const target = await this.target(path, signal);
68
+ const before = await this.ctx.fs.stat(target, signal);
69
+ if (!before && optional) return { target };
70
+ if (before?.type !== "file")
71
+ throw new Error("The plan file is missing or is not a regular file.");
72
+ const bytes = await this.ctx.fs.readBytes(target, signal, MAX_BYTES);
73
+ const after = await this.ctx.fs.stat(target, signal);
74
+ if (before.version !== after?.version)
75
+ throw new Error("The file changed during reading. Retry.");
76
+ const content = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
77
+ validateText(content);
78
+ return { target, version: before.version, content };
79
+ }
80
+
81
+ policy() {
82
+ return { mode: "workspace-write", workspaceRoot: this.directory };
83
+ }
84
+
85
+ async write(path, content, prior, signal) {
86
+ validateText(content);
87
+ if (Buffer.byteLength(content) > MAX_BYTES) throw new Error("Plan data exceeds 4 MiB.");
88
+ const target = await this.target(path, signal);
89
+ return this.ctx.fs.writeText(
90
+ target,
91
+ content,
92
+ prior?.version
93
+ ? { kind: "replaceIfVersion", version: prior.version }
94
+ : { kind: "createIfAbsent" },
95
+ signal,
96
+ this.policy(),
97
+ );
98
+ }
99
+
100
+ statePath(session) {
101
+ const key = createHash("sha256").update(session.id).digest("hex");
102
+ return join(this.directory, ".state", `${key}.json`);
103
+ }
104
+
105
+ async state(session, signal) {
106
+ const path = this.statePath(session);
107
+ const prior = await this.snapshot(path, signal, true);
108
+ const value =
109
+ prior.content === undefined
110
+ ? { version: 1, sessionId: session.id, plan: null }
111
+ : JSON.parse(prior.content);
112
+ if (
113
+ value.version !== 1 ||
114
+ value.sessionId !== session.id ||
115
+ (value.plan !== null && (typeof value.plan !== "object" || Array.isArray(value.plan)))
116
+ )
117
+ throw new Error("Invalid plan association record.");
118
+ return { path, prior, value };
119
+ }
120
+
121
+ path(record) {
122
+ if (
123
+ !record ||
124
+ typeof record.file !== "string" ||
125
+ basename(record.file) !== record.file ||
126
+ !/^[a-f0-9-]{36}$/.test(record.id) ||
127
+ !record.file.endsWith(`-${record.id.slice(0, 8)}.md`)
128
+ )
129
+ throw new Error("Invalid plan file identity.");
130
+ return join(this.directory, record.file);
131
+ }
132
+
133
+ async saveState(state, signal) {
134
+ const written = await this.write(
135
+ state.path,
136
+ JSON.stringify(state.value, null, 2) + "\n",
137
+ state.prior,
138
+ signal,
139
+ );
140
+ state.prior = { version: written.version };
141
+ }
142
+
143
+ inheritedPlan(session) {
144
+ if (!session.header.isSeeded) return;
145
+ const calls = new Set();
146
+ let inherited;
147
+ for (const event of session.snapshotEvents(0, session.inheritedEventCount)) {
148
+ if (event.type === "tool/call" && event.data.name === "plan_file")
149
+ calls.add(event.data.callId);
150
+ const message =
151
+ event.type === "tool/ptc-dispatch" && event.data.name === "plan_file"
152
+ ? event.data
153
+ : event.type === "tool/result" && calls.has(event.data.message.toolCallId)
154
+ ? event.data.message
155
+ : undefined;
156
+ if (!message || message.isError) continue;
157
+ for (const block of message.content ?? []) {
158
+ if (block.type !== "text") continue;
159
+ let value;
160
+ try {
161
+ value = JSON.parse(block.text);
162
+ } catch {
163
+ continue;
164
+ }
165
+ if (value.protocol === PROTOCOL && typeof value.content === "string") {
166
+ inherited = value.content;
167
+ }
168
+ }
169
+ }
170
+ return inherited;
171
+ }
172
+
173
+ async reserve(title, state, signal, forkPending = false) {
174
+ const id = randomUUID();
175
+ const date = new Date().toISOString().slice(0, 10);
176
+ const record = {
177
+ id,
178
+ file: `${date}-${slug(title)}-${id.slice(0, 8)}.md`,
179
+ ...(forkPending ? { forkPending: true } : {}),
180
+ };
181
+ state.value.plan = record;
182
+ // Persist identity first so an interrupted initial file write can retry the same path.
183
+ await this.saveState(state, signal);
184
+ return record;
185
+ }
186
+
187
+ async current(agent, signal, { title, create = false } = {}) {
188
+ const session = agent.session;
189
+ const episode = planEpisode(session);
190
+ const state = await this.state(session, signal);
191
+ let record = state.value.plan;
192
+ if (!record) {
193
+ const inherited = this.inheritedPlan(session);
194
+ if (inherited !== undefined) {
195
+ record = await this.reserve(inherited.split("\n")[0], state, signal, true);
196
+ } else if (create) {
197
+ record = await this.reserve(title, state, signal);
198
+ } else throw new Error("Create and save the plan with plan_file before requesting review.");
199
+ }
200
+ if (record.forkPending) {
201
+ const inherited = this.inheritedPlan(session);
202
+ if (inherited === undefined) throw new Error("The inherited plan receipt is unavailable.");
203
+ const copy = await this.snapshot(this.path(record), signal, true);
204
+ if (copy.content === undefined)
205
+ await this.write(this.path(record), inherited, undefined, signal);
206
+ delete record.forkPending;
207
+ await this.saveState(state, signal);
208
+ }
209
+ return { record, episode, path: this.path(record) };
210
+ }
211
+
212
+ async tool(args, exec) {
213
+ const { agent, signal } = exec;
214
+ if (!planning(agent)) throw new Error("plan_file is available in native Plan Mode.");
215
+ return this.exclusive(agent.session.id, async () => {
216
+ if (!planning(agent)) throw new Error("Plan Mode ended before this operation started.");
217
+ if (!["create", "read", "edit"].includes(args.action))
218
+ throw new Error("Use create, read, or edit.");
219
+ if (args.action === "create") {
220
+ validateText(args.content);
221
+ if (!/^#\s+\S/.test(args.content.trim()))
222
+ throw new Error("Start the Markdown plan with a # heading.");
223
+ if (typeof args.title !== "string" || !args.title.trim())
224
+ throw new Error("Supply a short task title.");
225
+ }
226
+ const current = await this.current(agent, signal, {
227
+ title: args.title,
228
+ create: args.action === "create",
229
+ });
230
+ const prior = await this.snapshot(current.path, signal, args.action === "create");
231
+ let content = prior.content;
232
+ if (args.action === "create") {
233
+ if (content !== undefined)
234
+ throw new Error("This plan already exists. Read it and apply localized edits.");
235
+ content = args.content;
236
+ }
237
+ if (args.action === "edit") {
238
+ if (typeof args.version !== "string" || args.version !== prior.version) {
239
+ throw new Error("The plan changed. Read it again and use the returned version.");
240
+ }
241
+ content = applyExactEdits(content, args.edits);
242
+ }
243
+ let version = prior.version;
244
+ if (args.action !== "read")
245
+ version = (await this.write(current.path, content, prior, signal)).version;
246
+ return { protocol: PROTOCOL, episode: current.episode, path: current.path, version, content };
247
+ });
248
+ }
249
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Plan Files",
4
+ "description": "Persistent Markdown plans with native DSH Plan Review and precise revisions."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "计划文件",
4
+ "description": "保存 Markdown 计划文件,通过精确编辑修订,并使用 DSH 原生计划审批。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "dsh-plan-files",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Persistent Markdown plan files with native DeepSeek Harness Plan Review",
5
+ "type": "module",
6
+ "keywords": [
7
+ "deepseek-harness",
8
+ "dsh",
9
+ "plan-mode",
10
+ "markdown",
11
+ "planning"
12
+ ],
13
+ "license": "MIT",
14
+ "workspaces": [
15
+ "test/runtimes/*"
16
+ ],
17
+ "exports": {
18
+ ".": "./index.js",
19
+ "./locale/*.json": "./locale/*.json"
20
+ },
21
+ "files": [
22
+ "index.js",
23
+ "lib/**/*.js",
24
+ "cordis.patch.yml",
25
+ "locale/*.json",
26
+ "README.md",
27
+ "README.zh-CN.md",
28
+ "LICENSE"
29
+ ],
30
+ "engines": {
31
+ "node": ">=22.0.0",
32
+ "dsh": "0.2.2-rc.3"
33
+ },
34
+ "dsh": {
35
+ "bundle": {
36
+ "patch": "./cordis.patch.yml"
37
+ }
38
+ },
39
+ "scripts": {
40
+ "format": "prettier --write .",
41
+ "format:check": "prettier --check .",
42
+ "lint": "npm run lint:js && npm run lint:markdown",
43
+ "lint:js": "eslint .",
44
+ "lint:markdown": "markdownlint-cli2",
45
+ "test": "node --test test/*.test.js",
46
+ "test:native": "node scripts/test-native.mjs",
47
+ "verify:package": "node scripts/verify-package.mjs",
48
+ "acceptance": "node scripts/acceptance.mjs",
49
+ "test:desktop": "node scripts/acceptance.mjs desktop",
50
+ "test:tui": "node scripts/acceptance.mjs tui",
51
+ "test:tui:config": "node scripts/acceptance.mjs tui-config",
52
+ "check": "npm run format:check && npm run lint && npm run test:native && npm run verify:package",
53
+ "prepublishOnly": "npm run check"
54
+ },
55
+ "devDependencies": {
56
+ "@eslint/js": "10.0.1",
57
+ "eslint": "10.12.0",
58
+ "globals": "17.13.0",
59
+ "markdownlint-cli2": "0.23.2",
60
+ "prettier": "3.9.5",
61
+ "semver": "7.7.3"
62
+ },
63
+ "repository": {
64
+ "type": "git",
65
+ "url": "git+https://github.com/paigeman/dsh-plan-files.git"
66
+ },
67
+ "homepage": "https://github.com/paigeman/dsh-plan-files#readme",
68
+ "bugs": {
69
+ "url": "https://github.com/paigeman/dsh-plan-files/issues"
70
+ },
71
+ "publishConfig": {
72
+ "access": "public",
73
+ "registry": "https://registry.npmjs.org"
74
+ }
75
+ }