dsh-stack-guardian 0.0.0-stage → 0.1.0-alpha.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +23 -3
  3. package/index.js +172 -0
  4. package/package.json +37 -6
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LuminariSoftwares
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
- # Temporary Holding Version
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.
1
+ # dsh-stack-guardian
2
+
3
+ A DeepSeek Harness plugin for [stack-guardian](https://github.com/LuminariSoftwares/stack-guardian). At the start of a
4
+ session it runs `stack-guardian doctor --json --quiet`. When the report is WARN or FAIL it adds one short line to the
5
+ conversation, for example that a node is unreachable or a model is not loaded. When everything is OK it adds nothing.
6
+
7
+ ## Needs
8
+
9
+ - Node 20+
10
+ - the Python CLI on PATH: `pip install stack-guardian`
11
+ - `STACK_GUARDIAN_NODES` set to your nodes file in the harness environment (see
12
+ [examples/nodes.json](https://github.com/LuminariSoftwares/stack-guardian/blob/main/examples/nodes.json))
13
+
14
+ ## Install
15
+
16
+ ```
17
+ npm install dsh-stack-guardian
18
+ ```
19
+
20
+ Then add the plugin to your harness configuration. Defaults: 5 s budget, injects on WARN and FAIL, at most 400
21
+ characters. A timeout or an unreadable report adds nothing, so a broken doctor never blocks a session.
22
+
23
+ MIT licensed.
package/index.js ADDED
@@ -0,0 +1,172 @@
1
+ // stack-guardian DSH plugin: one start-of-session line when the stack doctor reports WARN/FAIL.
2
+ // agent/session-start starts `stack-guardian doctor --json --quiet` (it reads the nodes file from $STACK_GUARDIAN_NODES);
3
+ // the first agent/pre-step adds the line (within budgetMs); OK/INFO, a timeout or a bad report add nothing. Zero DSH imports.
4
+ import { execFile } from "node:child_process";
5
+ import { randomUUID } from "node:crypto";
6
+ import { pathToFileURL } from "node:url";
7
+
8
+
9
+ export const name = "dsh-stack-guardian";
10
+ export const DEFAULTS = Object.freeze({
11
+ cli: "stack-guardian",
12
+ args: ["doctor", "--json", "--quiet"],
13
+ budgetMs: 5000,
14
+ injectOn: ["WARN", "FAIL"],
15
+ maxChars: 400,
16
+ });
17
+
18
+ const RANK = { OK: 0, INFO: 1, WARN: 2, FAIL: 3 };
19
+
20
+ const rankOf = (level) => (typeof level === "string" && Object.prototype.hasOwnProperty.call(RANK, level) ? RANK[level] : 0);
21
+
22
+ export function worstLevel(findings) {
23
+ if (!Array.isArray(findings) || findings.length === 0) return "OK";
24
+ let worst = "OK";
25
+ let worstRank = RANK.OK;
26
+ for (const f of findings) {
27
+ const level = f && typeof f === "object" ? f.level : undefined;
28
+ const r = rankOf(level);
29
+ if (r > worstRank) {
30
+ worstRank = r;
31
+ worst = level;
32
+ }
33
+ }
34
+ return worst;
35
+ }
36
+
37
+ export function parseReport(stdout) {
38
+ let parsed;
39
+ try {
40
+ parsed = JSON.parse(String(stdout || ""));
41
+ } catch {
42
+ return null;
43
+ }
44
+ if (parsed && typeof parsed === "object" && Array.isArray(parsed.findings)) return parsed;
45
+ return null;
46
+ }
47
+
48
+ export function buildLine(report, opts = {}) {
49
+ const injectOn = (opts && opts.injectOn) || DEFAULTS.injectOn;
50
+ const maxChars = (opts && opts.maxChars) || DEFAULTS.maxChars;
51
+ const findings = report && Array.isArray(report.findings) ? report.findings : [];
52
+ const worst = worstLevel(findings);
53
+ if (!injectOn.includes(worst)) return null;
54
+ const bad = findings
55
+ .map((f, i) => ({ f, i, r: rankOf(f && typeof f === "object" ? f.level : undefined) }))
56
+ .filter((e) => e.r >= RANK.WARN)
57
+ .sort((a, b) => (b.r - a.r) || (a.i - b.i))
58
+ .map((e) => (e.f && typeof e.f === "object" ? e.f : {}));
59
+ const items = bad.map((f) => `${f.node || "?"}: ${f.summary || f.code || "issue"}`);
60
+ const text = `[stack-guardian] ${worst}: ${bad.length} issue(s) — ${items.join("; ")} (run "stack-guardian doctor" for details)`;
61
+ if (text.length > maxChars) return text.slice(0, maxChars - 1) + "…";
62
+ return text;
63
+ }
64
+
65
+ export function createGuard({ run, sleep, budgetMs = DEFAULTS.budgetMs, injectOn = DEFAULTS.injectOn, maxChars = DEFAULTS.maxChars, log = () => {} }) {
66
+ const entries = new Map();
67
+ return {
68
+ start(key) {
69
+ if (entries.has(key)) return false;
70
+ entries.set(key, { done: false, promise: Promise.resolve().then(run) });
71
+ return true;
72
+ },
73
+ async lineFor(key) {
74
+ const entry = entries.get(key);
75
+ if (!entry || entry.done) return null;
76
+ entry.done = true;
77
+ const timeoutMarker = {};
78
+ const timer = Promise.resolve(sleep(budgetMs)).then(() => timeoutMarker);
79
+ try {
80
+ const out = await Promise.race([entry.promise, timer]);
81
+ if (out === timeoutMarker) {
82
+ log(`stack-guardian: doctor did not answer within ${budgetMs} ms; no warning added`);
83
+ return null;
84
+ }
85
+ const report = parseReport(out && out.stdout);
86
+ if (!report) {
87
+ log("stack-guardian: doctor printed no JSON report; no warning added");
88
+ return null;
89
+ }
90
+ return buildLine(report, { injectOn, maxChars });
91
+ } catch (e) {
92
+ log(`stack-guardian: doctor failed (${e && e.message}); no warning added`);
93
+ return null;
94
+ }
95
+ },
96
+ };
97
+ }
98
+
99
+ export function userMessage(text) {
100
+ return { id: randomUUID(), role: "user", content: [{ type: "text", text }], source: { kind: "plugin", plugin: name } };
101
+ }
102
+
103
+ export function agentKey(agent) {
104
+ return String((agent && (agent.id || (agent.session && agent.session.id))) || "default");
105
+ }
106
+
107
+ function spawnCli(opts) {
108
+ return new Promise((resolve) => {
109
+ execFile(opts.cli, opts.args, { timeout: opts.budgetMs + 1000, windowsHide: true }, (err, stdout) => {
110
+ resolve({ code: err ? (typeof err.code === "number" ? err.code : 1) : 0, stdout: String(stdout || "") });
111
+ });
112
+ });
113
+ }
114
+
115
+ export function apply(ctx, config = {}) {
116
+ const opts = { ...DEFAULTS, ...(config || {}) };
117
+ const guard = createGuard({
118
+ run: () => spawnCli(opts),
119
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
120
+ budgetMs: opts.budgetMs, injectOn: opts.injectOn, maxChars: opts.maxChars,
121
+ log: (line) => ctx.logger && ctx.logger.info(line),
122
+ });
123
+ ctx.on("agent/session-start", ({ agent, source }) => {
124
+ if (source === "startup") guard.start(agentKey(agent));
125
+ });
126
+ ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
127
+ const decision = await next();
128
+ if (decision.kind === "reject" || (signal && signal.aborted)) return decision;
129
+ const line = await guard.lineFor(agentKey(agent));
130
+ if (!line) return decision;
131
+ return { ...decision, messages: [...decision.messages, userMessage(line)] };
132
+ }, { prepend: true });
133
+ }
134
+
135
+ export async function selftest() {
136
+ const WARN = { findings: [{ level: "OK", node: "gpu-box-2", summary: "fine" }, { level: "WARN", node: "gpu-box", summary: "model not loaded", code: "model.not_loaded" }] };
137
+ const FAIL = { findings: [{ level: "WARN", node: "gpu-box", summary: "relayed" }, { level: "FAIL", node: "home-server", summary: "Ollama does not answer" }] };
138
+ const never = () => new Promise(() => {});
139
+ const now = () => Promise.resolve();
140
+ const guardWith = (run, sleep, logs) => createGuard({ run, sleep, budgetMs: 50, log: (l) => logs.push(l) });
141
+ const checks = [
142
+ ["defaults", () => DEFAULTS.budgetMs === 5000 && DEFAULTS.maxChars === 400 && DEFAULTS.injectOn.join(",") === "WARN,FAIL" && DEFAULTS.args.join(" ") === "doctor --json --quiet"],
143
+ ["worst_level", () => worstLevel([]) === "OK" && worstLevel(WARN.findings) === "WARN" && worstLevel(FAIL.findings) === "FAIL" && worstLevel([{ level: "INFO" }]) === "INFO"],
144
+ ["parse_report", () => parseReport(JSON.stringify(WARN)) !== null && parseReport("not json") === null && parseReport("{\"x\":1}") === null],
145
+ ["ok_and_info_add_nothing", () => buildLine({ findings: [{ level: "OK" }] }) === null && buildLine({ findings: [{ level: "INFO", node: "a", summary: "b" }] }) === null],
146
+ ["warn_line_exact", () => buildLine(WARN) === "[stack-guardian] WARN: 1 issue(s) — gpu-box: model not loaded (run \"stack-guardian doctor\" for details)"],
147
+ ["fail_first", () => buildLine(FAIL) === "[stack-guardian] FAIL: 2 issue(s) — home-server: Ollama does not answer; gpu-box: relayed (run \"stack-guardian doctor\" for details)"],
148
+ ["max_chars", () => { const big = { findings: Array.from({ length: 40 }, (_, i) => ({ level: "WARN", node: "n" + i, summary: "x".repeat(30) })) }; const l = buildLine(big); return l.length === 400 && l.endsWith("…"); }],
149
+ ["guard_warn_once", async () => { const logs = []; const g = guardWith(() => ({ code: 1, stdout: JSON.stringify(WARN) }), never, logs); g.start("a"); const first = await g.lineFor("a"); const second = await g.lineFor("a"); return first.startsWith("[stack-guardian] WARN") && second === null && logs.length === 0; }],
150
+ ["guard_start_twice", () => { const g = guardWith(() => ({}), never, []); return g.start("a") === true && g.start("a") === false; }],
151
+ ["guard_unknown_key_null", async () => (await guardWith(() => ({}), never, []).lineFor("zz")) === null],
152
+ ["guard_timeout_one_log", async () => { const logs = []; const g = guardWith(never, now, logs); g.start("a"); return (await g.lineFor("a")) === null && logs.length === 1 && logs[0].includes("did not answer within 50 ms"); }],
153
+ ["guard_bad_report_one_log", async () => { const logs = []; const g = guardWith(() => ({ code: 0, stdout: "Traceback" }), never, logs); g.start("a"); return (await g.lineFor("a")) === null && logs.length === 1; }],
154
+ ["guard_run_throws_one_log", async () => { const logs = []; const g = guardWith(() => { throw new Error("ENOENT"); }, never, logs); g.start("a"); return (await g.lineFor("a")) === null && logs.length === 1 && logs[0].includes("ENOENT"); }],
155
+ ["user_message_shape", () => { const m = userMessage("hi"); return m.role === "user" && m.content[0].text === "hi" && m.source.plugin === name && typeof m.id === "string"; }],
156
+ ["agent_key", () => agentKey({ id: "x" }) === "x" && agentKey({ session: { id: "s" } }) === "s" && agentKey(null) === "default"],
157
+ ];
158
+ let passed = 0;
159
+ for (const [n, fn] of checks) {
160
+ let ok = false;
161
+ try { ok = !!(await fn()); } catch (e) { console.log(` FAIL ${n} -- raised ${e && e.name}: ${e && e.message}`); }
162
+ if (ok) passed += 1;
163
+ console.log((ok ? " ok " : " FAIL ") + n);
164
+ }
165
+ console.log(`sg_dsh selftest: ${checks.length} checks, ${passed} passed, ${checks.length - passed} failed`);
166
+ return { checks: checks.length, passed, failed: checks.length - passed };
167
+ }
168
+
169
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href && process.argv.includes("--selftest")) {
170
+ const r = await selftest();
171
+ process.exit(r.checks > 0 && r.failed === 0 ? 0 : 1);
172
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
- {
2
- "name": "dsh-stack-guardian",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dsh-stack-guardian",
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "stack-guardian for the DeepSeek Harness: one start-of-session line when the stack doctor reports WARN/FAIL.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "files": [
12
+ "index.js",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "license": "MIT",
17
+ "author": "LuminariSoftwares",
18
+ "engines": {
19
+ "node": ">=20"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/LuminariSoftwares/stack-guardian.git",
24
+ "directory": "dsh"
25
+ },
26
+ "homepage": "https://github.com/LuminariSoftwares/stack-guardian#readme",
27
+ "bugs": {
28
+ "url": "https://github.com/LuminariSoftwares/stack-guardian/issues"
29
+ },
30
+ "keywords": [
31
+ "deepseek-harness",
32
+ "dsh",
33
+ "ollama",
34
+ "local-llm",
35
+ "health-check"
36
+ ]
37
+ }