dsh-limit-break 1.0.2 → 1.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,77 @@
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.1 — 2026-10-21
9
+
10
+ ### Fixed
11
+ - **The log could not tell you which copy was live.** `User-Agent` and every
12
+ `plugin-load.log` record now carry the version read from the installed `package.json`
13
+ instead of a hard-coded string, and mount records add `moduleDir`. A rolled-back or
14
+ hand-copied install is now visible in one line instead of a guess.
15
+ - **A doubly-activated plugin looked like a broken switch.** When a profile patch keeps a
16
+ second `insert` row for the same id, the loader mounts the plugin twice, the bundle switch
17
+ has nothing left to turn off, and the row switch is locked as *unaddressable*. Mounts are
18
+ now counted per store and a second live mount writes a `duplicate-apply` record with a
19
+ hint, so the misconfiguration is diagnosable from the log instead of from the symptom.
20
+
21
+ ## 1.2.0 — 2026-10-20
22
+
23
+ ### Fixed
24
+ - **A corrupt `facts.json` used to be silently replaced.** `loadStore` returned an empty
25
+ store on `SyntaxError`, and the next `memory_save` overwrote the unreadable file. The file
26
+ is now moved aside as `facts.json.corrupt-<epoch-ms>` before any new save, so recovery is
27
+ possible and `memory_stats.corrupt` is not a silent wipe.
28
+ - **`memory_recall({ limit })` accepted `Infinity`/negative/NaN.** `Number(input.limit) || 8`
29
+ let `Infinity` through to `slice()` (returns everything) and `-5` meant "all". The limit is
30
+ now clamped to `[1, 12]`, non-numeric falls back to 8.
31
+ - **A relative `DSH_HOME` put the store in the host's cwd.** Resolution now anchors a relative
32
+ value against `process.cwd()` and returns an absolute path, so the same store is found on
33
+ every launch.
34
+ - **`plugin-load.log` could grow forever.** The log is now trimmed to the last 500 lines and
35
+ capped at 256 KiB (a single un-newlined line cannot bypass the cap).
36
+ - **`resilient_fetch` buffered the whole response before clipping it.** One large page could
37
+ exhaust memory; the body is now read with a 2 MiB cap (`readCapped`), then clipped to 20 000
38
+ chars as before.
39
+ - `memory_save` rejects ids over 200 chars and statements over 20 000 chars instead of writing
40
+ them.
41
+
42
+ ### Added
43
+ - `test_plugin.mjs` grew six contract cases: limit clamping, corrupt-store recovery, log
44
+ trimming, relative `DSH_HOME` resolution, long-id rejection, plus the original round trip,
45
+ fetch ladder and alternate-host rewrite.
46
+ - README section "Known limits" — the honest list of what these tools still cannot do.
47
+
48
+ ## 1.1.0 — 2026-10-20
49
+
50
+ ### Added
51
+ - `MAINTAIN.md` — the maintenance runbook (probe → break → evolve → publish → record).
52
+ - `CHANGELOG.md` — this file.
53
+ - `tools/maintain.py` — three verbs: `status` (npm / GitHub / listing / drift),
54
+ `probe` (environment baseline with diff-against-previous), `verify` (contract test).
55
+ Shipped in the tarball so the loop is reproducible on any machine, not just this one.
56
+
57
+ ## 1.0.2 — 2026-10-20
58
+
59
+ ### Fixed
60
+ - Package metadata: `author` and `repository` now present in the published tarball.
61
+
62
+ ## 1.0.1 — 2026-10-20
63
+
64
+ ### Added
65
+ - Real implementation of the four tools (`memory_recall`, `memory_save`,
66
+ `resilient_fetch`, `memory_stats`) plus `dsh.bundle` so the app can mount it.
67
+
68
+ ## 1.0.0 — 2026-10-20
69
+
70
+ ### Added
71
+ - First published tarball. Shipped without metadata (superseded by 1.0.1).
72
+
73
+ ## 0.0.0-stage — 2026-10-20
74
+
75
+ ### Added
76
+ - Placeholder version created while npm staged publishing was blocking 1.0.0.
77
+ Not installable in any meaningful sense.
package/MAINTAIN.md ADDED
@@ -0,0 +1,128 @@
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 20:06 的真实状态)
112
+
113
+ - [x] **1.2.0 已上线**(2026-10-20T12:02:52Z):npm `latest` = `1.2.0`,GitHub `origin/main` =
114
+ `fd844a4`,`verify` PASS,`test_plugin.mjs` 6/6 PASS。用户 20:04 完成了 OTP 发布和推送。
115
+ `env.node_npm` 与 `release.dsh-limit-break` 两条事实已回写。
116
+ - [x] 旧定时任务 `schedule-803cdbdc`(会话 5133bee1)已由用户在面板删除;`storages/schedule.json`
117
+ 里只剩 `schedule-0b6c60ea`(hello world)和新的 `schedule-b3675d28`。无需再处理。
118
+ - [ ] 市场条目 PR `awesome-dsh-plugin/awesome-dsh-plugin#8296` 仍是 open;合并前 `status` 会一直报
119
+ `market listing not live yet`。找合并节奏,不要重提。
120
+ - [ ] npm 上还挂着占位包 `0.0.0-stage`(`stub: true`)。`npm deprecate` 也要 OTP(本轮 EOTP 失败);
121
+ 用户一条命令即可:`npm deprecate dsh-limit-break@0.0.0-stage "placeholder - use 1.2.0"`。
122
+ - [ ] `1.0.0` 是无元数据的旧包体(author/repository 都不在)。同样一条 `npm deprecate` 可清掉噪音(需 OTP)。
123
+ - [ ] `facts.json` 里 `env.gpu` 仍写着"no GPU compute benchmark was run"——已过时(GPU 实测 54.3×)。
124
+ - [x] 插件工具对**已经打开的会话**不可见:已在 README「Known limits」第 1 条写明
125
+ (tool list 是 per-session 快照,插件侧修不了)。事实 `harness.plugin-tool-visibility` 有实测。
126
+ - [ ] `resilient_fetch` 目前按"主机名别名"降级,可以继续加:`--resolve` 到已知 IP、
127
+ IPv6 优先、以及把成功路径写回记忆库(现在是只读阶梯)。
128
+ - [ ] 没有任何自动化测试覆盖 `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,11 @@
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
+ import { fileURLToPath } from 'node:url'
24
25
  import { promisify } from 'node:util'
25
26
 
26
27
  const execFileAsync = promisify(execFile)
@@ -28,13 +29,45 @@ const execFileAsync = promisify(execFile)
28
29
  export const name = 'limit-break'
29
30
  export const inject = ['tools']
30
31
 
31
- const UA = 'dsh-limit-break/1.0 (+local)'
32
+ /**
33
+ * Our own version, read from the package we were loaded out of.
34
+ *
35
+ * Hard-coding it means the value in `User-Agent` and in `plugin-load.log` can silently
36
+ * disagree with the tarball that is actually installed — which is exactly how a rolled-back
37
+ * 1.0.1 install kept looking like 1.2.0 during debugging.
38
+ */
39
+ let cachedVersion
40
+ function version() {
41
+ if (cachedVersion) return cachedVersion
42
+ try {
43
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
44
+ cachedVersion = String(pkg.version || '0.0.0-unknown')
45
+ } catch {
46
+ cachedVersion = '0.0.0-unknown'
47
+ }
48
+ return cachedVersion
49
+ }
50
+
51
+ const UA = `dsh-limit-break/${version()} (+local)`
32
52
  const MAX_TEXT = 20000
33
53
  const MAX_FACTS_RETURNED = 12
54
+ const MAX_BODY_BYTES = 2 * 1024 * 1024
55
+ const MAX_LOG_BYTES = 256 * 1024
56
+ const MAX_ID_CHARS = 200
34
57
 
35
- /** DSH_HOME is ~/.dsh (a symlink to the real data dir on this machine). */
58
+ /**
59
+ * DSH_HOME is ~/.dsh (a symlink to the real data dir on this machine).
60
+ *
61
+ * A relative DSH_HOME used to be used verbatim, so the store landed wherever the
62
+ * host's cwd happened to be — i.e. a different file per launch. Anchor it once.
63
+ */
36
64
  function resolveHome() {
37
- return process.env.DSH_HOME || join(homedir(), '.dsh')
65
+ const configured = process.env.DSH_HOME
66
+ if (configured && configured.trim()) {
67
+ const value = configured.trim()
68
+ return isAbsolute(value) ? value : resolve(process.cwd(), value)
69
+ }
70
+ return join(homedir(), '.dsh')
38
71
  }
39
72
 
40
73
  function resolveStoreDir(config) {
@@ -42,6 +75,32 @@ function resolveStoreDir(config) {
42
75
  return configured ? configured : join(resolveHome(), 'memory')
43
76
  }
44
77
 
78
+ /**
79
+ * Count live mounts of this plugin per store, in this process.
80
+ *
81
+ * The Plugins page can switch a plugin off, but a profile patch may still contain a second
82
+ * `insert` row for the same id — the loader happily mounts both, and then *neither* switch
83
+ * appears to work. That failure is invisible from the outside, so record it here: two live
84
+ * mounts pointing at one store is only ever a duplicate activation.
85
+ */
86
+ const LIVE_MOUNTS = Symbol.for('dsh-limit-break.live-mounts')
87
+
88
+ function registerMount(storeDir) {
89
+ const box = globalThis
90
+ if (!(box[LIVE_MOUNTS] instanceof Map)) box[LIVE_MOUNTS] = new Map()
91
+ const map = box[LIVE_MOUNTS]
92
+ const count = (map.get(storeDir) || 0) + 1
93
+ map.set(storeDir, count)
94
+ return {
95
+ count,
96
+ release() {
97
+ const left = (map.get(storeDir) || 1) - 1
98
+ if (left <= 0) map.delete(storeDir)
99
+ else map.set(storeDir, left)
100
+ }
101
+ }
102
+ }
103
+
45
104
  /**
46
105
  * Append one JSON line per load attempt to <store>/plugin-load.log.
47
106
  *
@@ -53,8 +112,21 @@ function diag(config, stage, extra) {
53
112
  try {
54
113
  const dir = resolveStoreDir(config)
55
114
  mkdirSync(dir, { recursive: true })
56
- const line = JSON.stringify({ at: new Date().toISOString(), pid: process.pid, stage, ...extra })
57
- appendFileSync(join(dir, 'plugin-load.log'), `${line}\n`)
115
+ const logFile = join(dir, 'plugin-load.log')
116
+ // The log is append-only by design; cap it so a long-lived host cannot grow it forever.
117
+ // Line-based trimming is not enough: a single un-newlined line (e.g. a stack trace
118
+ // dump or a truncated write) would survive the trim intact, so bound the bytes too.
119
+ try {
120
+ if (statSync(logFile).size > MAX_LOG_BYTES) {
121
+ let kept = readFileSync(logFile, 'utf8').split('\n').slice(-500).join('\n')
122
+ if (kept.length > MAX_LOG_BYTES) kept = kept.slice(-MAX_LOG_BYTES)
123
+ writeFileSync(logFile, kept.endsWith('\n') ? kept : `${kept}\n`)
124
+ }
125
+ } catch {
126
+ /* first write: no file yet */
127
+ }
128
+ const line = JSON.stringify({ at: new Date().toISOString(), pid: process.pid, version: version(), stage, ...extra })
129
+ appendFileSync(logFile, `${line}\n`)
58
130
  } catch {
59
131
  /* diagnostics must never break the host */
60
132
  }
@@ -66,17 +138,33 @@ function emptyStore() {
66
138
  return { schema_version: 1, kind: 'agent-memory-store', facts: [] }
67
139
  }
68
140
 
141
+ async function backupCorrupt(file) {
142
+ try {
143
+ await rename(file, `${file}.corrupt-${Date.now()}`)
144
+ } catch {
145
+ /* best effort: the next save still must not lose the file silently */
146
+ }
147
+ }
148
+
69
149
  async function loadStore(dir) {
70
150
  const file = join(dir, 'facts.json')
71
151
  try {
72
152
  const raw = await readFile(file, 'utf8')
73
153
  const parsed = JSON.parse(raw)
74
- if (!parsed || typeof parsed !== 'object') return { ...emptyStore(), file, existed: true, corrupt: true }
154
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
155
+ await backupCorrupt(file)
156
+ return { ...emptyStore(), file, existed: true, corrupt: true }
157
+ }
75
158
  if (!Array.isArray(parsed.facts)) parsed.facts = []
76
159
  return { ...parsed, file, existed: true }
77
160
  } catch (error) {
78
161
  if (error && error.code === 'ENOENT') return { ...emptyStore(), file, existed: false }
79
- if (error instanceof SyntaxError) return { ...emptyStore(), file, existed: true, corrupt: true }
162
+ if (error instanceof SyntaxError) {
163
+ // Never overwrite an unreadable store: move it aside so a later save starts clean
164
+ // without destroying evidence, and so the "corrupt" flag is not a silent wipe.
165
+ await backupCorrupt(file)
166
+ return { ...emptyStore(), file, existed: true, corrupt: true }
167
+ }
80
168
  throw error
81
169
  }
82
170
  }
@@ -163,14 +251,45 @@ function alternatesFor(url) {
163
251
  return out
164
252
  }
165
253
 
254
+ /**
255
+ * Read at most `cap` bytes off a fetch Response.
256
+ *
257
+ * `arrayBuffer()` buffered the whole body first: one 200 MB page took the host down
258
+ * before clip() ever ran. The tool only ever returns MAX_TEXT chars, so stop early.
259
+ */
260
+ async function readCapped(response, cap) {
261
+ const declared = Number(response.headers.get('content-length'))
262
+ if (Number.isFinite(declared) && declared > cap) {
263
+ // Still read a bounded prefix rather than buffering the whole thing.
264
+ }
265
+ if (!response.body) {
266
+ const buffer = await response.arrayBuffer()
267
+ return Buffer.from(buffer).subarray(0, cap).toString('utf8')
268
+ }
269
+ const reader = response.body.getReader()
270
+ const chunks = []
271
+ let total = 0
272
+ try {
273
+ while (total < cap) {
274
+ const { done, value } = await reader.read()
275
+ if (done) break
276
+ chunks.push(Buffer.from(value))
277
+ total += value.length
278
+ }
279
+ } finally {
280
+ reader.cancel().catch(() => {})
281
+ }
282
+ return Buffer.concat(chunks).subarray(0, cap).toString('utf8')
283
+ }
284
+
166
285
  async function fetchDirect(url, timeoutMs) {
167
286
  const response = await fetch(url, {
168
287
  redirect: 'follow',
169
288
  headers: { 'user-agent': UA, accept: '*/*' },
170
289
  signal: AbortSignal.timeout(timeoutMs)
171
290
  })
172
- const buffer = await response.arrayBuffer()
173
- return { status: response.status, ok: response.ok, text: Buffer.from(buffer).toString('utf8') }
291
+ const text = await readCapped(response, MAX_BODY_BYTES)
292
+ return { status: response.status, ok: response.ok, text }
174
293
  }
175
294
 
176
295
  async function fetchViaCurl(url, timeoutMs, family) {
@@ -226,9 +345,21 @@ export function apply(ctx, config) {
226
345
  diag(config, 'no-tools-service', { ctxKeys: ctx ? Object.keys(ctx).slice(0, 24) : [] })
227
346
  return
228
347
  }
229
- diag(config, 'mount', { storeDir: resolveStoreDir(config) })
230
-
231
348
  const storeDir = resolveStoreDir(config)
349
+ const mount = registerMount(storeDir)
350
+ diag(config, 'mount', {
351
+ storeDir,
352
+ moduleDir: dirname(fileURLToPath(import.meta.url)),
353
+ liveMounts: mount.count
354
+ })
355
+ if (mount.count > 1) {
356
+ diag(config, 'duplicate-apply', {
357
+ storeDir,
358
+ liveMounts: mount.count,
359
+ hint: 'the same plugin is mounted more than once (e.g. a bundle plus a manual insert row); switches will look broken'
360
+ })
361
+ }
362
+
232
363
  const timeoutMs = Number(config && config.requestTimeoutMs) || 12000
233
364
  const shellFallback = !(config && config.shellFallback === false)
234
365
 
@@ -237,6 +368,8 @@ export function apply(ctx, config) {
237
368
  return fn()
238
369
  }
239
370
 
371
+ effect(() => () => mount.release(), 'limit-break:lifetime')
372
+
240
373
  /* ---- memory_recall ------------------------------------------------ */
241
374
  effect(
242
375
  () =>
@@ -249,7 +382,7 @@ export function apply(ctx, config) {
249
382
  properties: {
250
383
  query: { type: 'string', description: 'Keywords to search for. Omit together with all=true to list everything.' },
251
384
  id: { type: 'string', description: 'Fetch one fact by exact id.' },
252
- all: { type: 'boolean', description: 'Return the whole store instead of a ranked subset.' },
385
+ all: { type: 'boolean', description: 'Return a large slice of the store (up to 48 facts) instead of the ranked subset.' },
253
386
  limit: { type: 'number', description: `Max facts to return (default 8, cap ${MAX_FACTS_RETURNED}).` }
254
387
  },
255
388
  additionalProperties: false
@@ -299,7 +432,10 @@ export function apply(ctx, config) {
299
432
  .sort((a, b) => b.score - a.score)
300
433
  .map((row) => row.fact)
301
434
  }
302
- const limit = Math.min(MAX_FACTS_RETURNED, Math.max(1, Number(input.limit) || 8))
435
+ // Number(input.limit) || 8 turned 0/NaN into 8 but let Infinity through to slice()
436
+ // (which returns everything) and gave no upper bound below the cap.
437
+ const requested = Number(input.limit)
438
+ const limit = Number.isFinite(requested) ? Math.min(MAX_FACTS_RETURNED, Math.max(1, Math.floor(requested))) : 8
303
439
  const slice = picked.slice(0, input.all ? MAX_FACTS_RETURNED * 4 : limit)
304
440
  if (!slice.length) {
305
441
  return {
@@ -356,6 +492,9 @@ export function apply(ctx, config) {
356
492
  const id = typeof input.id === 'string' ? input.id.trim() : ''
357
493
  const statement = typeof input.statement === 'string' ? input.statement.trim() : ''
358
494
  if (!id || !statement) return { ok: false, code: 'memory.invalid', message: 'Both id and statement are required.' }
495
+ if (id.length > MAX_ID_CHARS || statement.length > MAX_TEXT) {
496
+ return { ok: false, code: 'memory.invalid', message: `id must be <= ${MAX_ID_CHARS} chars and statement <= ${MAX_TEXT} chars.` }
497
+ }
359
498
  const store = await loadStore(storeDir)
360
499
  const now = new Date().toISOString()
361
500
  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.1",
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())