dsh-limit-break 1.0.2 → 1.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/CHANGELOG.md ADDED
@@ -0,0 +1,64 @@
1
+ # Changelog
2
+
3
+ All notable changes to `dsh-limit-break`. Format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), versions follow semver.
5
+
6
+ ## Unreleased
7
+
8
+ ## 1.2.0 — 2026-10-20
9
+
10
+ ### Fixed
11
+ - **A corrupt `facts.json` used to be silently replaced.** `loadStore` returned an empty
12
+ store on `SyntaxError`, and the next `memory_save` overwrote the unreadable file. The file
13
+ is now moved aside as `facts.json.corrupt-<epoch-ms>` before any new save, so recovery is
14
+ possible and `memory_stats.corrupt` is not a silent wipe.
15
+ - **`memory_recall({ limit })` accepted `Infinity`/negative/NaN.** `Number(input.limit) || 8`
16
+ let `Infinity` through to `slice()` (returns everything) and `-5` meant "all". The limit is
17
+ now clamped to `[1, 12]`, non-numeric falls back to 8.
18
+ - **A relative `DSH_HOME` put the store in the host's cwd.** Resolution now anchors a relative
19
+ value against `process.cwd()` and returns an absolute path, so the same store is found on
20
+ every launch.
21
+ - **`plugin-load.log` could grow forever.** The log is now trimmed to the last 500 lines and
22
+ capped at 256 KiB (a single un-newlined line cannot bypass the cap).
23
+ - **`resilient_fetch` buffered the whole response before clipping it.** One large page could
24
+ exhaust memory; the body is now read with a 2 MiB cap (`readCapped`), then clipped to 20 000
25
+ chars as before.
26
+ - `memory_save` rejects ids over 200 chars and statements over 20 000 chars instead of writing
27
+ them.
28
+
29
+ ### Added
30
+ - `test_plugin.mjs` grew six contract cases: limit clamping, corrupt-store recovery, log
31
+ trimming, relative `DSH_HOME` resolution, long-id rejection, plus the original round trip,
32
+ fetch ladder and alternate-host rewrite.
33
+ - README section "Known limits" — the honest list of what these tools still cannot do.
34
+
35
+ ## 1.1.0 — 2026-10-20
36
+
37
+ ### Added
38
+ - `MAINTAIN.md` — the maintenance runbook (probe → break → evolve → publish → record).
39
+ - `CHANGELOG.md` — this file.
40
+ - `tools/maintain.py` — three verbs: `status` (npm / GitHub / listing / drift),
41
+ `probe` (environment baseline with diff-against-previous), `verify` (contract test).
42
+ Shipped in the tarball so the loop is reproducible on any machine, not just this one.
43
+
44
+ ## 1.0.2 — 2026-10-20
45
+
46
+ ### Fixed
47
+ - Package metadata: `author` and `repository` now present in the published tarball.
48
+
49
+ ## 1.0.1 — 2026-10-20
50
+
51
+ ### Added
52
+ - Real implementation of the four tools (`memory_recall`, `memory_save`,
53
+ `resilient_fetch`, `memory_stats`) plus `dsh.bundle` so the app can mount it.
54
+
55
+ ## 1.0.0 — 2026-10-20
56
+
57
+ ### Added
58
+ - First published tarball. Shipped without metadata (superseded by 1.0.1).
59
+
60
+ ## 0.0.0-stage — 2026-10-20
61
+
62
+ ### Added
63
+ - Placeholder version created while npm staged publishing was blocking 1.0.0.
64
+ Not installable in any meaningful sense.
package/MAINTAIN.md ADDED
@@ -0,0 +1,132 @@
1
+ # MAINTAIN.md — 维护与进化 runbook
2
+
3
+ 这份文件是给"下一个我"看的。每轮维护从一个冷启动的会话开始,不共享上一轮的上下文;
4
+ 能指望的只有三样东西:**这个仓库**、**`D:\dsh-data\home\memory\facts.json`**、**`tools/maintain.py`**。
5
+
6
+ 方法沿用 2026-10-20 那两轮自测:**测极限 → 突破 → 进化插件 → 同步线上 → 记录**。
7
+
8
+ ---
9
+
10
+ ## 0. 开工(30 秒)
11
+
12
+ ```bash
13
+ cd D:/deepseek-harness/default-workspace/capability-demo/plugin/dsh-limit-break
14
+ PY="C:/Users/lenovo/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/python/python.exe"
15
+ $PY tools/maintain.py status # 我发布的版本在哪、PR 合没合、装的是不是 latest
16
+ $PY tools/maintain.py probe # 重新测一遍环境,和上次的 baseline 做 diff
17
+ $PY tools/maintain.py verify # 契约测试:4 个工具是否仍然注册成功
18
+ ```
19
+
20
+ 先读 `facts.json` 里 `topic` 为 `maintenance` / `release` 的条目,再看 `probe` 的
21
+ `diffs_vs_previous`——**diff 就是这一轮的线索**。若是空数组,说明环境没动,
22
+ 那就去 backlog 里挑一条,而不是假装有进展。
23
+
24
+ ## 1. 测极限
25
+
26
+ `probe` 覆盖:CPU 线程/GFLOPS、GPU 名称/显存/蒙特卡洛吞吐、nvidia-smi、CuPy 可用性、
27
+ PowerPoint COM、LibreOffice Kit、5 条网络探针、磁盘余量。
28
+
29
+ 读数落在 `C:\Users\lenovo\.dsh\memory\baseline-limit-break.json`,下一轮自动 diff。
30
+
31
+ **不要**只跑 probe 就交差。probe 的用途是发现"世界变了"(驱动升级、被封的域名活了、
32
+ CUDA 掉了、Office 卸载了),任何一项变化都可能是一个新的突破点。
33
+
34
+ ## 2. 找缺口
35
+
36
+ 按优先级从这几个来源取一条:
37
+
38
+ 1. `probe` 的 diff(环境变了 = 新机会或新故障)
39
+ 2. 用户当轮的原话(最高优先级,永远压倒自己的选题)
40
+ 3. 本文件末尾的 **Backlog**
41
+ 4. npm / GitHub 上别人的 issue(如果有)
42
+
43
+ 一轮只做**一件**。做不完的写回 Backlog,不要开第二战线。
44
+
45
+ ## 3. 突破
46
+
47
+ 规则和上次一样,也是这个项目唯一值得守的规则:
48
+
49
+ > 结论必须是**测出来的**,不是形容出来的。
50
+
51
+ - 能做就写脚本,用数字说话(秒、字节、比率、像素差、样本/秒)
52
+ - 做不到也写下来:**缺什么**(缺编译器?缺凭据?缺物理接口?),以及**试过什么**
53
+ - 失败要留在 Backlog 里,注明失败原因;下一轮不要重复同一个死胡同
54
+
55
+ ## 4. 进化
56
+
57
+ 改代码 → 跑 `verify` → 语义化版本:
58
+
59
+ | 改动 | 版本 |
60
+ | --- | --- |
61
+ | 新工具 / 不兼容改动 | minor(1.x.0) |
62
+ | 修 bug、改默认值、加参数 | patch(1.0.x) |
63
+
64
+ 同步两处副本(**仓库里的**才是源头):
65
+
66
+ ```
67
+ capability-demo/plugin/dsh-limit-break/ <- 改这里
68
+ D:\dsh-data\home\profiles\desktop\node_modules\dsh-limit-break\ <- 复制到这里才生效
69
+ ```
70
+
71
+ 只需重启 DSH 应用才加载新代码;**不要**替用户重启 GUI,告诉他自己重启。
72
+
73
+ ## 5. 同步线上
74
+
75
+ ```bash
76
+ # npm(先看 http 状态,409 是 staged publishing 残留,解法:把 latest 指走再发)
77
+ export PATH="/c/Users/lenovo/AppData/Local/nodejs:$PATH"
78
+ npm publish --no-fund --no-audit
79
+ npm view dsh-limit-break version dist-tags
80
+
81
+ # git(这台机器到 GitHub 会间歇性 Recv failure,重试 3 次再判断)
82
+ git add -A && git commit -m "..." && git push
83
+ ```
84
+
85
+ 市场目录(awesome-dsh-plugin)**不是自动同步的**:条目文件合并后才出现在市场里。
86
+ - 列表没上线时,先看 PR 状态;不要重复提同一个 PR
87
+ - 版本升级不需要重提条目(条目只指向仓库 URL),只有换包名/换分类才需要
88
+
89
+ ## 6. 记录
90
+
91
+ - `facts.json` 追加/更新 1–3 条,`topic` 用 `maintenance` 或 `release`
92
+ - 更新 `CHANGELOG.md` 的 `Unreleased`
93
+ - `baseline-limit-break.json` 由 probe 自动覆盖,不用手改
94
+
95
+ ---
96
+
97
+ ## 每轮的完成标准(DoD)
98
+
99
+ 一轮算做完,必须同时满足:
100
+
101
+ 1. `status` 里 `problems` 数组的每一条,要么被修掉,要么被解释成"不在我控制内"
102
+ 2. 有一句可以用数字反驳的话("X 从 A 变成 B")
103
+ 3. 代码有改动 → 版本升了 + `verify` PASS + npm 上是新版本
104
+ 4. 没有代码改动 → `CHANGELOG.md` 记一条"本轮无发布,原因:…"
105
+ 5. 有失败 → Backlog 里有一行带原因的记录
106
+
107
+ **最差的结果不是失败,是一轮结束后什么都没变、也没写下来。**
108
+
109
+ ---
110
+
111
+ ## Backlog(按 2026-10-20 结束时的真实状态)
112
+
113
+ - [ ] **1.2.0 待上线**:commit `69b726f` 只在本地。`git push origin main` 连续 3 次失败
114
+ (github.com:443 连接重置 / 连不上;api.github.com 仍 200,所以是 SNI 级封锁)。
115
+ `npm publish` 需要用户的 OTP,本轮未执行。恢复网络后跑:
116
+ `git push origin main && npm publish`(仓库与 `profiles/desktop/node_modules/dsh-limit-break`
117
+ 两份副本已同步且 `verify` PASS)。
118
+ - [ ] 旧定时任务 `schedule-803cdbdc`(会话 5133bee1)跨会话删不掉(`schedule_not_found`),
119
+ 已从 `storages/schedule.json` 摘行;运行中的 hub 会从内存回写,**重启后才彻底消失**,
120
+ 或由用户在 5133bee1 的定时任务面板手动删。INDEX.md 里留了自删提示。
121
+ - [ ] 市场条目 PR `awesome-dsh-plugin/awesome-dsh-plugin#8296` 仍是 open;合并前 `status` 会一直报
122
+ `market listing not live yet`。找合并节奏,不要重提。
123
+ - [ ] npm 上还挂着占位包 `0.0.0-stage`(`stub: true`)。可以考虑 `npm deprecate dsh-limit-break@0.0.0-stage "placeholder"`。
124
+ - [ ] `1.0.0` 是无元数据的旧包体(author/repository 都不在)。可以 deprecate 掉,减少噪音。
125
+ - [ ] `facts.json` 里 `env.gpu` 仍写着"no GPU compute benchmark was run"——已过时(GPU 实测 54.3×)。
126
+ - [ ] 插件工具对**已经打开的会话**不可见:插件在 `19:07:45` mount 成功(4 个工具都在),
127
+ 但那个时间点之前启动的会话,工具集里没有 `memory_*`。新会话才有。
128
+ 值得查清:是工具清单在会话创建时快照,还是 hub 与 agent 进程的工具注册面不同。
129
+ 查清后要么修(如果能在插件侧解决),要么写进 README 作为已知限制。
130
+ - [ ] `resilient_fetch` 目前按"主机名别名"降级,可以继续加:`--resolve` 到已知 IP、
131
+ IPv6 优先、以及把成功路径写回记忆库(现在是只读阶梯)。
132
+ - [ ] 没有任何自动化测试覆盖 `memory_save` 的并发写。单进程够用,多进程未验证。
package/README.md CHANGED
@@ -70,6 +70,24 @@ Writes are tmp-file + rename.
70
70
  * Cold: `dsh plugin remove dsh-limit-break`, then restart.
71
71
  * The store is not deleted by either. It lives in `$DSH_HOME/memory/` and is safe to keep.
72
72
 
73
+ ## Known limits
74
+
75
+ Measured, not guessed — each line is something a session actually hit.
76
+
77
+ * **Tools are visible only to sessions opened after the mount.** A session created before the
78
+ plugin mounted keeps its tool snapshot; new tools do not appear until a new session. Not fixable
79
+ from the plugin side (the tool list is materialised per session).
80
+ * **One writer per store.** Writes are tmp-file + rename, which is crash-safe, but two processes
81
+ writing `facts.json` concurrently still lose one update — there is no lock. One agent per
82
+ machine is the intended use.
83
+ * **The fetch ladder is hostname-level.** It does not defeat IP-level blocks, TLS interception,
84
+ or a proxy that terminates the connection; it does not skip certificate verification.
85
+ * **`memory_recall` ranks by keyword overlap only** (id/topic/tags/statement), no embeddings, no
86
+ stemming above the tokenisation in `tokenize()`. A query that shares no token with a fact will
87
+ miss it.
88
+ * **`resilient_fetch` reads at most 2 MiB per response** and returns at most 20 000 characters;
89
+ bigger payloads are truncated, not streamed.
90
+
73
91
  ## Privacy
74
92
 
75
93
  Nothing leaves the machine. `resilient_fetch` makes the request you asked for; the memory tools read
package/lib/index.js CHANGED
@@ -17,10 +17,10 @@
17
17
  */
18
18
 
19
19
  import { execFile } from 'node:child_process'
20
- import { appendFileSync, mkdirSync } from 'node:fs'
20
+ import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
21
21
  import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises'
22
22
  import { homedir } from 'node:os'
23
- import { dirname, join } from 'node:path'
23
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
24
24
  import { promisify } from 'node:util'
25
25
 
26
26
  const execFileAsync = promisify(execFile)
@@ -28,13 +28,26 @@ const execFileAsync = promisify(execFile)
28
28
  export const name = 'limit-break'
29
29
  export const inject = ['tools']
30
30
 
31
- const UA = 'dsh-limit-break/1.0 (+local)'
31
+ const UA = 'dsh-limit-break/1.2 (+local)'
32
32
  const MAX_TEXT = 20000
33
33
  const MAX_FACTS_RETURNED = 12
34
+ const MAX_BODY_BYTES = 2 * 1024 * 1024
35
+ const MAX_LOG_BYTES = 256 * 1024
36
+ const MAX_ID_CHARS = 200
34
37
 
35
- /** DSH_HOME is ~/.dsh (a symlink to the real data dir on this machine). */
38
+ /**
39
+ * DSH_HOME is ~/.dsh (a symlink to the real data dir on this machine).
40
+ *
41
+ * A relative DSH_HOME used to be used verbatim, so the store landed wherever the
42
+ * host's cwd happened to be — i.e. a different file per launch. Anchor it once.
43
+ */
36
44
  function resolveHome() {
37
- return process.env.DSH_HOME || join(homedir(), '.dsh')
45
+ const configured = process.env.DSH_HOME
46
+ if (configured && configured.trim()) {
47
+ const value = configured.trim()
48
+ return isAbsolute(value) ? value : resolve(process.cwd(), value)
49
+ }
50
+ return join(homedir(), '.dsh')
38
51
  }
39
52
 
40
53
  function resolveStoreDir(config) {
@@ -53,8 +66,21 @@ function diag(config, stage, extra) {
53
66
  try {
54
67
  const dir = resolveStoreDir(config)
55
68
  mkdirSync(dir, { recursive: true })
69
+ const logFile = join(dir, 'plugin-load.log')
70
+ // The log is append-only by design; cap it so a long-lived host cannot grow it forever.
71
+ // Line-based trimming is not enough: a single un-newlined line (e.g. a stack trace
72
+ // dump or a truncated write) would survive the trim intact, so bound the bytes too.
73
+ try {
74
+ if (statSync(logFile).size > MAX_LOG_BYTES) {
75
+ let kept = readFileSync(logFile, 'utf8').split('\n').slice(-500).join('\n')
76
+ if (kept.length > MAX_LOG_BYTES) kept = kept.slice(-MAX_LOG_BYTES)
77
+ writeFileSync(logFile, kept.endsWith('\n') ? kept : `${kept}\n`)
78
+ }
79
+ } catch {
80
+ /* first write: no file yet */
81
+ }
56
82
  const line = JSON.stringify({ at: new Date().toISOString(), pid: process.pid, stage, ...extra })
57
- appendFileSync(join(dir, 'plugin-load.log'), `${line}\n`)
83
+ appendFileSync(logFile, `${line}\n`)
58
84
  } catch {
59
85
  /* diagnostics must never break the host */
60
86
  }
@@ -66,17 +92,33 @@ function emptyStore() {
66
92
  return { schema_version: 1, kind: 'agent-memory-store', facts: [] }
67
93
  }
68
94
 
95
+ async function backupCorrupt(file) {
96
+ try {
97
+ await rename(file, `${file}.corrupt-${Date.now()}`)
98
+ } catch {
99
+ /* best effort: the next save still must not lose the file silently */
100
+ }
101
+ }
102
+
69
103
  async function loadStore(dir) {
70
104
  const file = join(dir, 'facts.json')
71
105
  try {
72
106
  const raw = await readFile(file, 'utf8')
73
107
  const parsed = JSON.parse(raw)
74
- if (!parsed || typeof parsed !== 'object') return { ...emptyStore(), file, existed: true, corrupt: true }
108
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
109
+ await backupCorrupt(file)
110
+ return { ...emptyStore(), file, existed: true, corrupt: true }
111
+ }
75
112
  if (!Array.isArray(parsed.facts)) parsed.facts = []
76
113
  return { ...parsed, file, existed: true }
77
114
  } catch (error) {
78
115
  if (error && error.code === 'ENOENT') return { ...emptyStore(), file, existed: false }
79
- if (error instanceof SyntaxError) return { ...emptyStore(), file, existed: true, corrupt: true }
116
+ if (error instanceof SyntaxError) {
117
+ // Never overwrite an unreadable store: move it aside so a later save starts clean
118
+ // without destroying evidence, and so the "corrupt" flag is not a silent wipe.
119
+ await backupCorrupt(file)
120
+ return { ...emptyStore(), file, existed: true, corrupt: true }
121
+ }
80
122
  throw error
81
123
  }
82
124
  }
@@ -163,14 +205,45 @@ function alternatesFor(url) {
163
205
  return out
164
206
  }
165
207
 
208
+ /**
209
+ * Read at most `cap` bytes off a fetch Response.
210
+ *
211
+ * `arrayBuffer()` buffered the whole body first: one 200 MB page took the host down
212
+ * before clip() ever ran. The tool only ever returns MAX_TEXT chars, so stop early.
213
+ */
214
+ async function readCapped(response, cap) {
215
+ const declared = Number(response.headers.get('content-length'))
216
+ if (Number.isFinite(declared) && declared > cap) {
217
+ // Still read a bounded prefix rather than buffering the whole thing.
218
+ }
219
+ if (!response.body) {
220
+ const buffer = await response.arrayBuffer()
221
+ return Buffer.from(buffer).subarray(0, cap).toString('utf8')
222
+ }
223
+ const reader = response.body.getReader()
224
+ const chunks = []
225
+ let total = 0
226
+ try {
227
+ while (total < cap) {
228
+ const { done, value } = await reader.read()
229
+ if (done) break
230
+ chunks.push(Buffer.from(value))
231
+ total += value.length
232
+ }
233
+ } finally {
234
+ reader.cancel().catch(() => {})
235
+ }
236
+ return Buffer.concat(chunks).subarray(0, cap).toString('utf8')
237
+ }
238
+
166
239
  async function fetchDirect(url, timeoutMs) {
167
240
  const response = await fetch(url, {
168
241
  redirect: 'follow',
169
242
  headers: { 'user-agent': UA, accept: '*/*' },
170
243
  signal: AbortSignal.timeout(timeoutMs)
171
244
  })
172
- const buffer = await response.arrayBuffer()
173
- return { status: response.status, ok: response.ok, text: Buffer.from(buffer).toString('utf8') }
245
+ const text = await readCapped(response, MAX_BODY_BYTES)
246
+ return { status: response.status, ok: response.ok, text }
174
247
  }
175
248
 
176
249
  async function fetchViaCurl(url, timeoutMs, family) {
@@ -249,7 +322,7 @@ export function apply(ctx, config) {
249
322
  properties: {
250
323
  query: { type: 'string', description: 'Keywords to search for. Omit together with all=true to list everything.' },
251
324
  id: { type: 'string', description: 'Fetch one fact by exact id.' },
252
- all: { type: 'boolean', description: 'Return the whole store instead of a ranked subset.' },
325
+ all: { type: 'boolean', description: 'Return a large slice of the store (up to 48 facts) instead of the ranked subset.' },
253
326
  limit: { type: 'number', description: `Max facts to return (default 8, cap ${MAX_FACTS_RETURNED}).` }
254
327
  },
255
328
  additionalProperties: false
@@ -299,7 +372,10 @@ export function apply(ctx, config) {
299
372
  .sort((a, b) => b.score - a.score)
300
373
  .map((row) => row.fact)
301
374
  }
302
- const limit = Math.min(MAX_FACTS_RETURNED, Math.max(1, Number(input.limit) || 8))
375
+ // Number(input.limit) || 8 turned 0/NaN into 8 but let Infinity through to slice()
376
+ // (which returns everything) and gave no upper bound below the cap.
377
+ const requested = Number(input.limit)
378
+ const limit = Number.isFinite(requested) ? Math.min(MAX_FACTS_RETURNED, Math.max(1, Math.floor(requested))) : 8
303
379
  const slice = picked.slice(0, input.all ? MAX_FACTS_RETURNED * 4 : limit)
304
380
  if (!slice.length) {
305
381
  return {
@@ -356,6 +432,9 @@ export function apply(ctx, config) {
356
432
  const id = typeof input.id === 'string' ? input.id.trim() : ''
357
433
  const statement = typeof input.statement === 'string' ? input.statement.trim() : ''
358
434
  if (!id || !statement) return { ok: false, code: 'memory.invalid', message: 'Both id and statement are required.' }
435
+ if (id.length > MAX_ID_CHARS || statement.length > MAX_TEXT) {
436
+ return { ok: false, code: 'memory.invalid', message: `id must be <= ${MAX_ID_CHARS} chars and statement <= ${MAX_TEXT} chars.` }
437
+ }
359
438
  const store = await loadStore(storeDir)
360
439
  const now = new Date().toISOString()
361
440
  const record = {
package/package.json CHANGED
@@ -1,48 +1,51 @@
1
- {
2
- "name": "dsh-limit-break",
3
- "version": "1.0.2",
4
- "description": "Durable cross-session memory and a fetch ladder that survives hostname-keyed blocking — four small tools for DeepSeek Harness.",
5
- "type": "module",
6
- "main": "lib/index.js",
7
- "exports": {
8
- ".": "./lib/index.js",
9
- "./package.json": "./package.json"
10
- },
11
- "files": [
12
- "lib/",
13
- "cordis.patch.yml",
14
- "README.md",
15
- "LICENSE"
16
- ],
17
- "keywords": [
18
- "deepseek",
19
- "deepseek-harness",
20
- "dsh",
21
- "dsh-plugin",
22
- "memory",
23
- "long-term-memory",
24
- "fetch",
25
- "network"
26
- ],
27
- "engines": {
28
- "node": ">=22.6"
29
- },
30
- "license": "MIT",
31
- "author": {
32
- "name": "mapingyue",
33
- "email": "2067984403@qq.com"
34
- },
35
- "repository": {
36
- "type": "git",
37
- "url": "git+https://github.com/Ma354/dsh-limit-break.git"
38
- },
39
- "homepage": "https://github.com/Ma354/dsh-limit-break#readme",
40
- "bugs": {
41
- "url": "https://github.com/Ma354/dsh-limit-break/issues"
42
- },
43
- "dsh": {
44
- "bundle": {
45
- "patch": "./cordis.patch.yml"
46
- }
47
- }
48
- }
1
+ {
2
+ "name": "dsh-limit-break",
3
+ "version": "1.2.0",
4
+ "description": "Durable cross-session memory and a fetch ladder that survives hostname-keyed blocking — four small tools for DeepSeek Harness.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "files": [
12
+ "lib/",
13
+ "cordis.patch.yml",
14
+ "README.md",
15
+ "LICENSE",
16
+ "tools/",
17
+ "MAINTAIN.md",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "keywords": [
21
+ "deepseek",
22
+ "deepseek-harness",
23
+ "dsh",
24
+ "dsh-plugin",
25
+ "memory",
26
+ "long-term-memory",
27
+ "fetch",
28
+ "network"
29
+ ],
30
+ "engines": {
31
+ "node": ">=22.6"
32
+ },
33
+ "license": "MIT",
34
+ "author": {
35
+ "name": "mapingyue",
36
+ "email": "2067984403@qq.com"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/Ma354/dsh-limit-break.git"
41
+ },
42
+ "homepage": "https://github.com/Ma354/dsh-limit-break#readme",
43
+ "bugs": {
44
+ "url": "https://github.com/Ma354/dsh-limit-break/issues"
45
+ },
46
+ "dsh": {
47
+ "bundle": {
48
+ "patch": "./cordis.patch.yml"
49
+ }
50
+ }
51
+ }
@@ -0,0 +1,326 @@
1
+ #!/usr/bin/env python3
2
+ """dsh-limit-break maintenance kit.
3
+
4
+ One script, three verbs. Every verb prints something a human can read and
5
+ writes JSON next to the memory store so the next round can diff against it.
6
+
7
+ python tools/maintain.py status # where the plugin stands, right now
8
+ python tools/maintain.py probe # re-measure the environment, diff vs last
9
+ python tools/maintain.py verify # contract test + install sanity
10
+
11
+ The loop this belongs to (see MAINTAIN.md):
12
+ probe -> find a limit that moved
13
+ break -> prove it with a measurement, not an opinion
14
+ evolve -> turn it into a tool or a fix
15
+ publish-> version, npm, git, listing
16
+ record -> facts.json + CHANGELOG
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import os
22
+ import platform
23
+ import socket
24
+ import subprocess
25
+ import sys
26
+ import time
27
+ import urllib.error
28
+ import urllib.request
29
+ from datetime import datetime, timezone, timedelta
30
+ from pathlib import Path
31
+
32
+ HOME = Path(os.environ.get("DSH_HOME", Path.home() / ".dsh"))
33
+ TZ = timezone(timedelta(hours=8))
34
+ PKG = "dsh-limit-break"
35
+ REPO = "Ma354/dsh-limit-break"
36
+ LIST_REPO = "awesome-dsh-plugin/awesome-dsh-plugin"
37
+ HERE = Path(__file__).resolve().parent.parent # .../dsh-limit-break
38
+ PROFILE = HOME / "profiles" / "desktop"
39
+ STORE = HOME / "memory"
40
+ BASELINE = STORE / "baseline-limit-break.json"
41
+ GPU_LIBS = Path(r"D:\deepseek-harness\default-workspace\capability-demo\breakthrough\gpu\libs")
42
+
43
+
44
+ def now() -> str:
45
+ return datetime.now(TZ).isoformat(timespec="seconds")
46
+
47
+
48
+ def get(url: str, timeout: float = 12.0):
49
+ """-> (http_code, seconds, body_text). Never raises."""
50
+ t0 = time.time()
51
+ req = urllib.request.Request(url, headers={"User-Agent": f"{PKG}-maintain/1"})
52
+ try:
53
+ with urllib.request.urlopen(req, timeout=timeout) as r:
54
+ return r.status, time.time() - t0, r.read().decode("utf-8", "replace")
55
+ except urllib.error.HTTPError as e:
56
+ return e.code, time.time() - t0, ""
57
+ except Exception as e: # noqa: BLE001
58
+ return f"ERR:{type(e).__name__}", time.time() - t0, ""
59
+
60
+
61
+ def get_json(url: str):
62
+ code, secs, body = get(url)
63
+ if isinstance(code, int) and 200 <= code < 300:
64
+ try:
65
+ return code, secs, json.loads(body)
66
+ except Exception: # noqa: BLE001
67
+ pass
68
+ return code, secs, None
69
+
70
+
71
+ def sh(cmd: list[str], timeout: float = 30.0) -> str:
72
+ try:
73
+ p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
74
+ return (p.stdout or "").strip() or (p.stderr or "").strip()
75
+ except Exception as e: # noqa: BLE001
76
+ return f"ERR:{type(e).__name__}"
77
+
78
+
79
+ # --------------------------------------------------------------------------- status
80
+ def cmd_status() -> int:
81
+ out: dict = {"checked_at": now(), "problems": []}
82
+
83
+ local = {}
84
+ try:
85
+ local = json.loads((PROFILE / "node_modules" / PKG / "package.json").read_text(encoding="utf-8"))
86
+ except Exception: # noqa: BLE001
87
+ out["problems"].append("installed copy missing under the profile")
88
+ out["installed_version"] = local.get("version")
89
+ out["installed_has_bundle"] = bool(local.get("dsh", {}).get("bundle"))
90
+
91
+ prof = {}
92
+ try:
93
+ prof = json.loads((PROFILE / "package.json").read_text(encoding="utf-8"))
94
+ except Exception: # noqa: BLE001
95
+ pass
96
+ bundles = prof.get("dsh", {}).get("profile", {}).get("bundles", [])
97
+ out["in_dependencies"] = prof.get("dependencies", {}).get(PKG)
98
+ out["in_bundles"] = PKG in bundles
99
+ out["bundle_position"] = bundles.index(PKG) if PKG in bundles else None
100
+ if not out["in_bundles"]:
101
+ out["problems"].append("not listed in dsh.profile.bundles -> the app will never load it")
102
+
103
+ try:
104
+ repo_ver = json.loads((HERE / "package.json").read_text(encoding="utf-8")).get("version")
105
+ except Exception: # noqa: BLE001
106
+ repo_ver = None
107
+ out["repo_version"] = repo_ver
108
+
109
+ code, _, reg = get_json(f"https://registry.npmjs.org/{PKG}?t={int(time.time())}")
110
+ out["npm_http"] = code
111
+ if reg:
112
+ out["npm_latest"] = reg.get("dist-tags", {}).get("latest")
113
+ out["npm_versions"] = sorted(reg.get("versions", {}))
114
+ if out["npm_latest"] != out["installed_version"]:
115
+ out["problems"].append(
116
+ f"drift: installed {out['installed_version']} != npm latest {out['npm_latest']}")
117
+ if repo_ver and repo_ver != out["npm_latest"]:
118
+ out["problems"].append(
119
+ f"release pending: repo at {repo_ver}, npm latest {out['npm_latest']} (needs npm publish)")
120
+ else:
121
+ out["problems"].append(f"npm registry unreachable ({code})")
122
+
123
+ code, _, gh = get_json(f"https://api.github.com/repos/{REPO}")
124
+ out["github_http"] = code
125
+ if gh:
126
+ out["github_pushed_at"] = gh.get("pushed_at")
127
+ out["github_stars"] = gh.get("stargazers_count")
128
+ out["github_description"] = gh.get("description")
129
+
130
+ code, _, raw = get(f"https://raw.githubusercontent.com/{LIST_REPO}/main/data/plugins/Ma354__{PKG}.yml")
131
+ out["listing_http"] = code
132
+ out["listed_in_market"] = code == 200
133
+
134
+ code, _, prs = get_json(
135
+ f"https://api.github.com/search/issues?q=repo:{LIST_REPO}+is:pr+{PKG}+in:title")
136
+ if prs and prs.get("items"):
137
+ pr = prs["items"][0]
138
+ out["pr"] = {"number": pr["number"], "state": pr["state"], "merged": bool(pr.get("pull_request", {}).get("merged_at")),
139
+ "url": pr["html_url"]}
140
+ if not out["listed_in_market"]:
141
+ out["problems"].append(f"market listing not live yet (PR #{pr['number']} {pr['state']})")
142
+ else:
143
+ out["pr"] = None
144
+
145
+ log = STORE / "plugin-load.log"
146
+ if log.exists():
147
+ lines = [l for l in log.read_text(encoding="utf-8").splitlines() if l.strip()]
148
+ if lines:
149
+ try:
150
+ out["last_mount"] = json.loads(lines[-1])
151
+ except Exception: # noqa: BLE001
152
+ out["last_mount"] = lines[-1]
153
+
154
+ print(json.dumps(out, ensure_ascii=False, indent=2))
155
+ return 0
156
+
157
+
158
+ # ---------------------------------------------------------------------------- probe
159
+ def _cupy_probe() -> dict:
160
+ res: dict = {}
161
+ if not GPU_LIBS.exists():
162
+ return {"available": False, "why": f"libs dir missing: {GPU_LIBS}"}
163
+ sys.path.insert(0, str(GPU_LIBS))
164
+ binx = GPU_LIBS / "bin"
165
+ if binx.exists() and hasattr(os, "add_dll_directory"):
166
+ try:
167
+ os.add_dll_directory(str(binx))
168
+ except Exception: # noqa: BLE001
169
+ pass
170
+ try:
171
+ import cupy as cp # noqa: F401
172
+ except Exception as e: # noqa: BLE001
173
+ return {"available": False, "why": f"{type(e).__name__}: {e}"}
174
+ try:
175
+ dev = cp.cuda.Device(0)
176
+ props = cp.cuda.runtime.getDeviceProperties(0)
177
+ res["device"] = props["name"].decode() if isinstance(props["name"], bytes) else str(props["name"])
178
+ res["vram_mib"] = round(dev.mem_info[1] / 2**20, 1)
179
+ n = 1 << 26
180
+ x = cp.random.random(n, dtype=cp.float32)
181
+ y = cp.random.random(n, dtype=cp.float32)
182
+ for _ in range(3): # warm up kernels + allocator
183
+ cp.count_nonzero(x * x + y * y <= 1.0)
184
+ cp.cuda.Stream.null.synchronize()
185
+ best = min(_mc_once(cp, x, y, n) for _ in range(3))
186
+ res["mc_samples_per_sec"] = round(n / best)
187
+ res["mc_seconds"] = round(best, 4)
188
+ res["available"] = True
189
+ except Exception as e: # noqa: BLE001
190
+ res["available"] = False
191
+ res["why"] = f"runtime: {type(e).__name__}: {e}"
192
+ return res
193
+
194
+
195
+ def _mc_once(cp, x, y, n):
196
+ cp.cuda.Stream.null.synchronize()
197
+ t0 = time.perf_counter()
198
+ cp.count_nonzero(x * x + y * y <= 1.0)
199
+ cp.cuda.Stream.null.synchronize()
200
+ return time.perf_counter() - t0
201
+
202
+
203
+ def _cpu_gflops() -> float | None:
204
+ try:
205
+ import numpy as np
206
+ n = 1024
207
+ a = np.random.random((n, n))
208
+ b = np.random.random((n, n))
209
+ a @ b
210
+ t0 = time.perf_counter()
211
+ for _ in range(3):
212
+ a @ b
213
+ dt = (time.perf_counter() - t0) / 3
214
+ return round(2 * n ** 3 / dt / 1e9, 1)
215
+ except Exception: # noqa: BLE001
216
+ return None
217
+
218
+
219
+ NET_PROBES = [
220
+ ("baseline.example", "https://example.com/"),
221
+ ("npm", "https://registry.npmjs.org/"),
222
+ ("github-api", "https://api.github.com/"),
223
+ ("wikipedia-direct", "https://en.wikipedia.org/wiki/Artificial_intelligence"),
224
+ ("wikimedia-api", "https://api.wikimedia.org/core/v1/wikipedia/en/page/Artificial_intelligence"),
225
+ ]
226
+
227
+
228
+ def cmd_probe() -> int:
229
+ snap: dict = {"probed_at": now(), "host": socket.gethostname()}
230
+ snap["os"] = f"{platform.system()} {platform.release()}"
231
+ snap["python"] = platform.python_version()
232
+ node = Path(r"D:\dsh文件\resources\runtime\primary-runtime\dependencies\node\bin\node.exe")
233
+ snap["node"] = sh([str(node), "-v"]) if node.exists() else "missing"
234
+ snap["cpu_threads"] = os.cpu_count()
235
+ snap["cpu_gflops"] = _cpu_gflops()
236
+
237
+ nvsmi = sh(["nvidia-smi", "--query-gpu=name,memory.total,driver_version",
238
+ "--format=csv,noheader"], timeout=20)
239
+ snap["nvidia_smi"] = nvsmi or "unavailable"
240
+ snap["cupy"] = _cupy_probe()
241
+
242
+ ppt = Path(r"C:\Program Files\Microsoft Office\Root\Office16\POWERPNT.EXE")
243
+ snap["powerpoint_com"] = ppt.exists()
244
+ lo = Path(r"D:\dsh文件\resources\app.asar.unpacked\dsh\node_modules\@deepseek-ai\libreoffice-kit\lib\cli.js")
245
+ snap["libreoffice_kit"] = lo.exists()
246
+
247
+ net = {}
248
+ for name, url in NET_PROBES:
249
+ code, secs, body = get(url, timeout=8.0)
250
+ net[name] = {"code": code, "seconds": round(secs, 3), "bytes": len(body)}
251
+ snap["network"] = net
252
+
253
+ try:
254
+ import shutil
255
+ free, total = shutil.disk_usage("D:\\")
256
+ snap["disk_d_free_gib"] = round(free / 2**30, 1)
257
+ snap["disk_d_total_gib"] = round(total / 2**30, 1)
258
+ except Exception: # noqa: BLE001
259
+ pass
260
+
261
+ prev = None
262
+ if BASELINE.exists():
263
+ try:
264
+ prev = json.loads(BASELINE.read_text(encoding="utf-8"))
265
+ except Exception: # noqa: BLE001
266
+ prev = None
267
+
268
+ diffs: list[str] = []
269
+ if prev:
270
+ if prev.get("cupy", {}).get("available") != snap["cupy"].get("available"):
271
+ diffs.append(f"cupy availability {prev['cupy'].get('available')} -> {snap['cupy'].get('available')}")
272
+ p_mc = (prev.get("cupy") or {}).get("mc_samples_per_sec")
273
+ n_mc = snap["cupy"].get("mc_samples_per_sec")
274
+ if p_mc and n_mc and abs(n_mc - p_mc) / p_mc > 0.25:
275
+ diffs.append(f"gpu mc throughput {p_mc} -> {n_mc} (>25%)")
276
+ if prev.get("cpu_threads") != snap["cpu_threads"]:
277
+ diffs.append(f"cpu threads {prev.get('cpu_threads')} -> {snap['cpu_threads']}")
278
+ for k, v in snap["network"].items():
279
+ pv = (prev.get("network") or {}).get(k, {}).get("code")
280
+ if pv != v["code"]:
281
+ diffs.append(f"network {k}: {pv} -> {v['code']}")
282
+ if prev.get("powerpoint_com") != snap["powerpoint_com"]:
283
+ diffs.append("powerpoint COM availability changed")
284
+ snap["previous_probed_at"] = prev.get("probed_at")
285
+ else:
286
+ diffs.append("no previous baseline - this run becomes the baseline")
287
+
288
+ snap["diffs_vs_previous"] = diffs
289
+ STORE.mkdir(parents=True, exist_ok=True)
290
+ BASELINE.write_text(json.dumps(snap, ensure_ascii=False, indent=2), encoding="utf-8")
291
+ print(json.dumps(snap, ensure_ascii=False, indent=2))
292
+ print(f"\nbaseline written to {BASELINE}", file=sys.stderr)
293
+ return 0
294
+
295
+
296
+ # --------------------------------------------------------------------------- verify
297
+ def cmd_verify() -> int:
298
+ node = Path(r"D:\dsh文件\resources\runtime\primary-runtime\dependencies\node\bin\node.exe")
299
+ test = HERE.parent / "test_plugin.mjs"
300
+ if not test.exists():
301
+ test = Path(r"D:\deepseek-harness\default-workspace\capability-demo\plugin\test_plugin.mjs")
302
+ if not test.exists():
303
+ print(json.dumps({"contract_test": "SKIP", "why": f"test file not found near {HERE}"}))
304
+ return 1
305
+ p = subprocess.run([str(node), str(test)], capture_output=True, text=True, timeout=120)
306
+ print(json.dumps({
307
+ "checked_at": now(),
308
+ "contract_test": "PASS" if p.returncode == 0 else "FAIL",
309
+ "returncode": p.returncode,
310
+ "stdout": (p.stdout or "").strip()[-1500:],
311
+ "stderr": (p.stderr or "").strip()[-800:],
312
+ }, ensure_ascii=False, indent=2))
313
+ return 0 if p.returncode == 0 else 1
314
+
315
+
316
+ def main() -> int:
317
+ verb = (sys.argv[1] if len(sys.argv) > 1 else "").lower()
318
+ table = {"status": cmd_status, "probe": cmd_probe, "verify": cmd_verify}
319
+ if verb not in table:
320
+ print(__doc__)
321
+ return 2
322
+ return table[verb]()
323
+
324
+
325
+ if __name__ == "__main__":
326
+ sys.exit(main())