dsh-decision-layer 0.5.5 → 0.6.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/README.en.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  `dsh-decision-layer` adds structured, explicitly scoped decisions to the DeepSeek Harness (DSH) agent loop, backed by a pluggable adjudication backend. Dangerous-call gating, output self-check, tool narrowing, and loop prevention hook into the agent loop as automatic interventions.
6
6
 
7
- > **0.5.5 is a preview release.** The plugin works, but how much real value the adjudication interventions add is still being explored — every threshold is an unvalidated heuristic default. Treat it as something to observe, not a proven guarantee of impact. See [ROADMAP.md](<ROADMAP.md>) for scope and progress.
7
+ > **0.6.0 is a preview release.** The plugin works, but how much real value the adjudication interventions add is still being explored — every threshold is an unvalidated heuristic default. Treat it as something to observe, not a proven guarantee of impact. See [ROADMAP.md](<ROADMAP.md>) for scope and progress.
8
8
 
9
9
  ## Installation
10
10
 
@@ -46,7 +46,8 @@ Restart `dsh web` and refresh after installing or updating: the host and client
46
46
  - **Decision-analysis view** — an in-session "Decision analysis" tab (`conversation.view`, alongside chat and trajectory, naturally scoped per session) that reads the persisted log read-only and shows a process profile (per-point attempts and outcome distribution, mean self-check score), a quality-trend threshold backtest, and a decision-accuracy summary, and lets you rate each decision correct / wrong / unsure. Ratings share one source with the intervention panel: a rating on either surface writes to the same log, keyed by decision id, latest wins. Read-only over logs, append-only for annotations; it changes no decision behavior.
47
47
  - **Per-feature switches** — the config page has an independent switch for the danger gate, output self-check, and tool narrowing, all on by default; turning one off drops that intervention. The loop guard is not covered by these switches.
48
48
  - **Persisted decision log** — beyond the in-memory panel, decisions are written in full per session to `~/.config/dsh-decision-layer/logs` for research. Files roll by running-instance port and date (`decisions-<port>-YYYY-MM-DD.jsonl`), are batched, and retained for 30 days. Writing is best-effort: a failed flush drops that batch and never breaks the decision path.
49
+ - **Persisted session metrics** — the panel's live metrics (dock count, per-decision-point cards, recent decision log) no longer reset to zero after a restart. Each session's live state is mirrored, keyed by session id (not port), to `~/.config/dsh-decision-layer/state/<sessionId>.json`, written debounced and atomically on every change and retained for 30 days. A resumed session restores from that snapshot; if it has no snapshot yet but has persisted log history (a session predating this mechanism, or whose snapshot was pruned), a seed is reconstructed from the logs across all ports by session id — the one exception is "actual" gate outcomes (observed allow/deny), which are not in the log and resume from zero. Writing is likewise best-effort and never enters the decision path.
49
50
 
50
51
  ## Safety boundary and development
51
52
 
52
- Automatic intervention only subtracts: the gate only denies, narrowing only removes tools, and neither grants new permissions. The gate defers to native DSH approval on backend failure rather than allowing; self-check, narrowing, and loop-guard errors skip intervention. The redacted summary sent to the backend carries only tool name and command/path with secret redaction — never file content. Node.js `>=20.11`; `npm test` and `npm run build:client` run local checks. Rebuild and commit `lib/client.js` with any client change. 0.5.5 is a preview: the interventions work, but their real value and thresholds are still being explored — feedback on misjudgments and feel observed in the decision log is welcome.
53
+ Automatic intervention only subtracts: the gate only denies, narrowing only removes tools, and neither grants new permissions. The gate defers to native DSH approval on backend failure rather than allowing; self-check, narrowing, and loop-guard errors skip intervention. The redacted summary sent to the backend carries only tool name and command/path with secret redaction — never file content. Node.js `>=20.11`; `npm test` and `npm run build:client` run local checks. Rebuild and commit `lib/client.js` with any client change. 0.6.0 is a preview: the interventions work, but their real value and thresholds are still being explored — feedback on misjudgments and feel observed in the decision log is welcome.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  DeepSeek Harness(DSH)的结构化裁决插件。它把有明确判断标准的问题交给同协议的裁决后端,供 agent 在需要时使用,并在 agent loop 上接入危险门控、产出自检、工具收窄和防循环等自动介入。
6
6
 
7
- > **0.5.5 是体验版。** 插件功能已可用,但裁决介入能带来多少实际价值仍在探索中——各决策点的阈值都是未经验证的启发式默认值,建议先以观察心态体验,别当成经过验证的效果保证。功能与后续进度以 [ROADMAP.md](<ROADMAP.md>) 为准。
7
+ > **0.6.0 是体验版。** 插件功能已可用,但裁决介入能带来多少实际价值仍在探索中——各决策点的阈值都是未经验证的启发式默认值,建议先以观察心态体验,别当成经过验证的效果保证。功能与后续进度以 [ROADMAP.md](<ROADMAP.md>) 为准。
8
8
 
9
9
  ## 安装
10
10
 
@@ -40,12 +40,13 @@ dsh plugin --profile web add file:/绝对路径/dsh-decision-layer
40
40
  - **产出自检**:回合结束用评分量表给最终产出打分(0–2,按各档位概率加权,可能是小数)。默认只提示、不打断;可开启「低分补完」,得分偏低且模型有把握时以你的名义追加一次补完提示,同一回合最多补一次。
41
41
  - **任务完成核对**:当用户明确列出多个交付条件(编号 / 项目符号 / 多命令)时,回合结束前用单选逐项判定「已满足 / 未满足 / 证据不足」,工具证据优先、回复自述不算证据;确定性提取、不推断隐含期望。默认只观察、可配 steer,与产出自检并存、指标分列。
42
42
  - **产出质量趋势告警**:建在自检数据上的只读提醒。连续多次高置信低分时,把输入框旁触发按钮的图标从灰变橙、变红,hover 提示可能是任务变难或模型波动、建议调整 prompt 或更换模型。纯提示、不驱动自动干预;高置信门槛 / 连续轮数 / 严重档三个阈值可配(默认 0.6 / 3 / 5),偏保守、待实测校准。
43
- - **工具收窄**:回合开始时用 noul 逐个判断可选工具与本轮任务的相关性,摘掉用不上的(相关性概率低于摘除阈值,默认 0.3、可配),只在宿主已允许的集合内取交集、不扩权。默认真正生效,可切到「仅观察」只记录不改工具集。三重保护:核心工具(读写、编辑、Shell、检索、待办,以及问用户、目标、技能、交付、后台作业、协作等 agent 元能力)始终保留、不参与判定;可选工具超过候选上限(默认 20,可配)时自动降为仅观察;保留下来不足 5 个时视为判定不可信、跳过。**保留工具前缀**白名单里的工具(默认含 `mcp__openviking`、`team_task_`)也始终保留、不参与判定,适合记忆 / 检索、协作这类常驻、按需触发的工具。
43
+ - **工具收窄**:回合开始时用 noul 逐个判断可选工具与本轮任务的相关性,摘掉用不上的(相关性概率低于摘除阈值,默认 0.3、可配),只在宿主已允许的集合内取交集、不扩权。默认真正生效,可切到「仅观察」只记录不改工具集。三重保护:核心工具(读写、编辑、Shell、检索、待办,以及问用户、目标、技能、交付、后台作业、协作等 agent 元能力)始终保留、不参与判定;可选工具超过候选上限(默认 20,可配)时自动降为仅观察;保留下来不足 5 个时视为判定不可信、跳过。**保留工具前缀**白名单里的工具(默认含 `mcp__openviking`、`team_task_`)也始终保留、不参与判定,适合记忆 / 检索、协作这类常驻、按需触发的工具。**分批策略**按后端上下文容量自适应(`batchMode`,默认 `auto`):大上下文后端(如 Jev)一次请求判完全部工具;小上下文后端(如本地 tev1,约 2050 token 单请求上限)在遇到上下文超限错误时自动降级为「每工具一次请求、并发执行」并记住,之后直接走拆分,不再反复探测。也可显式设 `single`(始终整批)或 `split`(始终逐工具)。某个工具的拆分请求失败时该工具保守保留。
44
44
  - **防循环**:确定性判断,不走后端;同一调用连续重复超过阈值即拒绝,打断死循环。始终生效,不在决策点开关范围内。
45
45
  - **会话面板**:输入框下方的 dock 触发器弹出面板,展示自动裁决指标(评估数、失败回退、模型建议与实际结果分列)、会话总开关和决策日志;无自动裁决时显示空态。总开关关闭只暂停自动介入,不影响手动裁决。
46
46
  - **决策分析页**:会话内「决策分析」tab(`conversation.view`,与对话/轨迹平级、天然按会话隔离),基于已落盘日志做只读聚合,展示过程画像(各决策点触发数与结果分布、自检平均分)、质量趋势阈值回测、判断准确度汇总,并可对每条决策标注「判对 / 判错 / 说不准」。标注与介入面板同源:任一处标注都写入同一份日志、按决策 id 关联、取最新。只读日志、只追加标注,不改任何决策行为。
47
47
  - **决策点开关**:详情页配置里,危险门控、产出自检、工具收窄各有独立开关,默认全开;关掉某个决策点就不再对应地介入。防循环不在此范围。
48
48
  - **决策日志落盘**:决策记录在内存面板之外,还按会话全量落盘到 `~/.config/dsh-decision-layer/logs`,供研究回看。文件按运行实例端口和日期滚动切分(`decisions-<端口>-YYYY-MM-DD.jsonl`),批量写入,保留 30 天。写盘为尽力而为,失败只丢当批、不影响决策路径。
49
+ - **会话指标持久化**:面板的实时指标(dock 计数、各决策点卡片、最近决策日志)在重启后不再归零。每个会话的实时状态按会话 id(非端口)另存一份快照到 `~/.config/dsh-decision-layer/state/<会话id>.json`,每次计数变化防抖写盘、原子落盘,保留 30 天。同一会话恢复时优先读该快照续算;若尚无快照但有历史决策日志(如早于本机制、或快照已被清理的会话),则跨全部端口按会话 id 从日志重建种子续算——唯一例外是「实际结果」(gate 观测到的放行 / 拒绝)无法从日志重建,重启后从零重新累计。写盘同为尽力而为,失败绝不进入决策路径。
49
50
 
50
51
  ## 安全边界
51
52
 
@@ -53,4 +54,4 @@ dsh plugin --profile web add file:/绝对路径/dsh-decision-layer
53
54
 
54
55
  ## 开发
55
56
 
56
- 服务端使用 Node.js `>=20.11`(`.mjs`,无需构建);客户端用 TypeScript + esbuild 构建。`npm test` 跑本地测试,`npm run build:client` 生成 `lib/client.js`。改动客户端后需重建并连同 `lib/client.js` 一起提交,否则 GitHub 安装拿到的是旧 bundle。0.5.5 为体验版:介入能力已可用,但实际价值与阈值仍在探索,欢迎反馈决策日志观察到的误判与体感。
57
+ 服务端使用 Node.js `>=20.11`(`.mjs`,无需构建);客户端用 TypeScript + esbuild 构建。`npm test` 跑本地测试,`npm run build:client` 生成 `lib/client.js`。改动客户端后需重建并连同 `lib/client.js` 一起提交,否则 GitHub 安装拿到的是旧 bundle。0.6.0 为体验版:介入能力已可用,但实际价值与阈值仍在探索,欢迎反馈决策日志观察到的误判与体感。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-decision-layer",
3
- "version": "0.5.5",
3
+ "version": "0.6.0",
4
4
  "description": "A structured decision layer for the DeepSeek Harness agent loop: a danger-call gate, output self-check, tool narrowing, and loop guard backed by a pluggable adjudication model.",
5
5
  "keywords": [
6
6
  "dsh",
@@ -97,7 +97,7 @@ function validCheck(value) {
97
97
 
98
98
  function validNarrow(value) {
99
99
  if (!safeObject(value)) return undefined;
100
- if (Object.keys(value).some(key => !['mode', 'threshold', 'keepPrefixes', 'maxCandidates'].includes(key))) throw new Error('Invalid narrowing settings');
100
+ if (Object.keys(value).some(key => !['mode', 'threshold', 'keepPrefixes', 'maxCandidates', 'batchMode'].includes(key))) throw new Error('Invalid narrowing settings');
101
101
  const narrow = {};
102
102
  if (value.mode !== undefined) {
103
103
  if (value.mode !== 'observe' && value.mode !== 'enforce') throw new Error('Invalid narrowing settings');
@@ -124,6 +124,17 @@ function validNarrow(value) {
124
124
  if (!Number.isSafeInteger(value.maxCandidates) || value.maxCandidates < 1 || value.maxCandidates > 200) throw new Error('Invalid narrowing settings');
125
125
  narrow.maxCandidates = value.maxCandidates;
126
126
  }
127
+ // Per-request batching strategy for the relevance pass, chosen by backend
128
+ // context capacity. 'single' sends every tool in one systemone request (best
129
+ // for large-context backends like Jev — one call). 'split' sends one request
130
+ // per tool concurrently (required for small-context backends like tev1, whose
131
+ // ~2050-token prompt limit rejects a many-tool request). 'auto' (default)
132
+ // tries 'single' first and falls back to 'split' only after a context-overflow
133
+ // http-error, so Jev stays at one call and tev1 self-corrects.
134
+ if (value.batchMode !== undefined) {
135
+ if (!['auto', 'single', 'split'].includes(value.batchMode)) throw new Error('Invalid narrowing settings');
136
+ narrow.batchMode = value.batchMode;
137
+ }
127
138
  return narrow;
128
139
  }
129
140
 
package/service/dsh.mjs CHANGED
@@ -10,7 +10,8 @@ import { createNarrowing } from './narrowing.mjs';
10
10
  import { createTaskCompletion } from './task-completion.mjs';
11
11
  import { createLoopGuard } from './loop-guard.mjs';
12
12
  import { createLogStore } from './log-store.mjs';
13
- import { analyzeSessionLogs } from './log-analyze.mjs';
13
+ import { createStateStore } from './state-store.mjs';
14
+ import { analyzeSessionLogs, reconstructSessionSeed } from './log-analyze.mjs';
14
15
 
15
16
  export const name = 'dsh-decision-layer';
16
17
  export const inject = ['tools', 'skills'];
@@ -100,7 +101,23 @@ export async function apply(ctx, options = {}) {
100
101
  // The research log sink is attached once the web server reveals the instance
101
102
  // port (used in the file name); until then decision logs stay in memory only.
102
103
  let logStore;
103
- const sessions = createSessionState({ onLog: entry => logStore?.append(entry) });
104
+ // Durable per-session mirror of the live decision counters/log, keyed by
105
+ // session id (not port), so a resumed session's panel survives an instance
106
+ // restart instead of resetting to zero. Independent of the JSONL research log.
107
+ const stateStore = createStateStore();
108
+ const sessions = createSessionState({
109
+ onLog: entry => logStore?.append(entry),
110
+ // Restore a resumed session from its durable snapshot; if it has none yet but
111
+ // has persisted JSONL decision history (e.g. a session that predates this
112
+ // persistence, or whose snapshot was pruned), reconstruct a seed from the
113
+ // logs instead. Logs are read across all ports and filtered by the globally
114
+ // unique session id, so a changed instance port never orphans the history.
115
+ loadState: async id => (await stateStore.load(id)) ?? reconstructSessionSeed(id, {
116
+ trendConfig: (await resolveConfig({ path })).checkSettings,
117
+ }).catch(() => undefined),
118
+ persistState: (id, state) => stateStore.save(id, state),
119
+ });
120
+ if (typeof ctx.effect === 'function') ctx.effect(() => () => { void stateStore.dispose(); });
104
121
  const gate = createDangerGate({
105
122
  evaluate: (input, request) => backend.evaluate(input, request),
106
123
  sessions,
@@ -185,6 +202,10 @@ export async function apply(ctx, options = {}) {
185
202
  const agent = payload?.agent;
186
203
  const id = agent?.session?.id;
187
204
  const turn = payload?.turn;
205
+ // Rehydrate this session's persisted counters/log on its first step this
206
+ // process, before any gate/check/narrow/complete event mutates them, so a
207
+ // resumed session continues from its saved totals instead of from zero.
208
+ if (typeof id === 'string') await sessions.ensureLoaded(id);
188
209
  if (typeof id === 'string' && Number.isInteger(turn) && await featureOn('narrow')) {
189
210
  const state = narrowedTurns.get(id);
190
211
  if (!state || state.turn !== turn) {
@@ -1,4 +1,5 @@
1
1
  import { createReadableStream } from './log-read.mjs';
2
+ import { advanceRun, severityOf } from './quality-trend.mjs';
2
3
 
3
4
  // Offline analysis over the persisted decision JSONL logs. Pure aggregation:
4
5
  // given a stream of records (decision events + annotation events) for one
@@ -153,3 +154,79 @@ export async function analyzeSessionLogs(sessionId, { dir, port, trendConfig, re
153
154
  }
154
155
  return analyzeSession(records, trendConfig);
155
156
  }
157
+
158
+ // Reconstruct a live session-state seed (the counter shape session-state keeps,
159
+ // plus the recent decision log) from this session's folded decisions. Used to
160
+ // bridge a restart for a session that has persisted JSONL history but no state
161
+ // snapshot yet, so its panel resumes from its real totals instead of from zero.
162
+ //
163
+ // Faithful for every counter because each feature logs exactly one record per
164
+ // record*() call with the same outcome — with one documented exception:
165
+ // gate.actual (observed tool outcomes) is never logged, so it starts at zero and
166
+ // resumes as new tool results arrive. The check trend run/severity is replayed
167
+ // with the same advanceRun/severityOf semantics the live path uses.
168
+ export function buildSeed(decisions, { maxLog = 50, trendConfig = {} } = {}) {
169
+ const ordered = [...decisions.values()].filter(record => DECISION_KINDS.has(record.kind)).sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
170
+ const seed = {
171
+ attempts: 0, failures: 0,
172
+ gate: { attempts: 0, failures: 0, ask: 0, deny: 0, allow: 0, actual: { allow: 0, deny: 0, error: 0 } },
173
+ check: { attempts: 0, failures: 0, low: 0, run: 0, severity: 'normal' },
174
+ narrow: { attempts: 0, failures: 0, applied: 0, dropped: 0 },
175
+ complete: { attempts: 0, failures: 0, unsatisfied: 0, satisfied: 0, insufficient: 0, steered: 0 },
176
+ log: [],
177
+ };
178
+ const minConfidence = typeof trendConfig.trendMinConfidence === 'number' ? trendConfig.trendMinConfidence : 0.6;
179
+ const thresholds = { trendRun: trendConfig.trendRun ?? 3, trendSevereRun: trendConfig.trendSevereRun ?? 5 };
180
+ let run = 0;
181
+ for (const record of ordered) {
182
+ const bucket = seed[record.kind];
183
+ seed.attempts++;
184
+ bucket.attempts++;
185
+ const isError = record.outcome === 'error';
186
+ if (isError) { seed.failures++; bucket.failures++; }
187
+ if (record.kind === 'gate') {
188
+ if (['allow', 'ask', 'deny'].includes(record.outcome)) bucket[record.outcome]++;
189
+ } else if (record.kind === 'check') {
190
+ if (!isError) {
191
+ if (record.outcome === 'low') bucket.low++;
192
+ // Replay the trend run exactly as recordCheck does: lowScore keys off the
193
+ // 'low' outcome, confident off the logged confidence vs the threshold.
194
+ const confident = typeof record.confidence === 'number' && Number.isFinite(record.confidence) && record.confidence >= minConfidence;
195
+ run = advanceRun(run, { lowScore: record.outcome === 'low', confident });
196
+ }
197
+ } else if (record.kind === 'narrow') {
198
+ if (record.outcome === 'applied') {
199
+ bucket.applied++;
200
+ if (Number.isSafeInteger(record.dropped) && record.dropped > 0) bucket.dropped += record.dropped;
201
+ }
202
+ } else if (record.kind === 'complete') {
203
+ if (!isError) {
204
+ if (Number.isSafeInteger(record.satisfied)) bucket.satisfied += record.satisfied;
205
+ if (Number.isSafeInteger(record.unsatisfied)) bucket.unsatisfied += record.unsatisfied;
206
+ if (Number.isSafeInteger(record.insufficient)) bucket.insufficient += record.insufficient;
207
+ if (record.steered === true) bucket.steered++;
208
+ }
209
+ }
210
+ }
211
+ seed.check.run = run;
212
+ seed.check.severity = severityOf(run, thresholds);
213
+ // The recent-log list: the newest decisions, as plain records (drop sessionId,
214
+ // which the live log does not carry). Already in the panel-record shape.
215
+ seed.log = ordered.slice(-maxLog).map(record => { const { sessionId, ...rest } = record; return rest; });
216
+ return seed;
217
+ }
218
+
219
+ // Read one session's persisted JSONL and reconstruct its live state seed, or
220
+ // undefined when it has no decision history. Streams files like analyzeSessionLogs.
221
+ export async function reconstructSessionSeed(sessionId, { dir, port, trendConfig, maxLog, readStream = createReadableStream } = {}) {
222
+ if (typeof sessionId !== 'string' || !sessionId.trim()) return undefined;
223
+ const records = [];
224
+ for await (const record of readStream({ dir, port })) {
225
+ if (!isObject(record)) continue;
226
+ if (record.sessionId === sessionId) records.push(record);
227
+ }
228
+ if (records.length === 0) return undefined;
229
+ const { decisions } = foldSession(records);
230
+ if (decisions.size === 0) return undefined;
231
+ return buildSeed(decisions, { maxLog, trendConfig });
232
+ }
@@ -77,8 +77,8 @@ export function createManagerRoutes({ path, sessions, backend, logStore, analyze
77
77
  } catch { return { connected: false, reason: 'unavailable', effectiveUrl }; }
78
78
  },
79
79
  }),
80
- route('metrics', { GET: req => sessions.snapshot(sessionId(req)) }),
81
- route('log', { GET: req => ({ entries: sessions.snapshot(sessionId(req)).log ?? [] }) }),
80
+ route('metrics', { GET: async req => { const id = sessionId(req); await sessions.ensureLoaded?.(id); return sessions.snapshot(id); } }),
81
+ route('log', { GET: async req => { const id = sessionId(req); await sessions.ensureLoaded?.(id); return { entries: sessions.snapshot(id).log ?? [] }; } }),
82
82
  // Read-only analysis over the persisted decision logs for one session. Returns
83
83
  // only aggregates and annotation counts — never raw log rows — so gate command
84
84
  // / path fragments are not echoed back to the browser.
@@ -110,9 +110,10 @@ export function createManagerRoutes({ path, sessions, backend, logStore, analyze
110
110
  },
111
111
  }),
112
112
  route('session', {
113
- GET: req => sessions.snapshot(sessionId(req)),
113
+ GET: async req => { const id = sessionId(req); await sessions.ensureLoaded?.(id); return sessions.snapshot(id); },
114
114
  PUT: async req => {
115
115
  const body = await readBody(req);
116
+ await sessions.ensureLoaded?.(body.sessionId);
116
117
  sessions.setEnabled(body.sessionId, body.enabled);
117
118
  return sessions.snapshot(body.sessionId);
118
119
  },
@@ -82,15 +82,22 @@ export function relevanceQuestions(state, tools) {
82
82
  // C. if narrowing would leave fewer than `minKeep` tools total, the verdict is
83
83
  // treated as untrustworthy and no restriction is applied.
84
84
  export function createNarrowing({ evaluate, sessions, settings, coreTools = DEFAULT_CORE_TOOLS,
85
- keepPrefixes = DEFAULT_KEEP_PREFIXES, minCandidates = 2, maxCandidates = 20, minKeep = 5 } = {}) {
85
+ keepPrefixes = DEFAULT_KEEP_PREFIXES, minCandidates = 2, maxCandidates = 20, minKeep = 5, splitConcurrency = 8 } = {}) {
86
86
  if (typeof evaluate !== 'function') throw new Error('Narrowing requires an evaluator');
87
87
  const core = new Set(Array.isArray(coreTools) ? coreTools.filter(name => typeof name === 'string') : []);
88
88
  const defaultPrefixes = Array.isArray(keepPrefixes) ? keepPrefixes.filter(prefix => typeof prefix === 'string' && prefix) : [];
89
+ const concurrency = Number.isSafeInteger(splitConcurrency) && splitConcurrency >= 1 ? splitConcurrency : 8;
90
+ // Set once a 'single' (whole-batch) pass hits a context-overflow http-error:
91
+ // from then on 'auto' sends one request per tool. A large-context backend
92
+ // (Jev) never trips this and stays at one call; a small-context backend
93
+ // (tev1, ~2050-token prompt) self-corrects after the first failure.
94
+ let adaptiveSplit = false;
89
95
  const resolveSettings = async () => {
90
96
  let raw = {};
91
97
  try { raw = (typeof settings === 'function' ? await settings() : settings) ?? {}; } catch { raw = {}; }
92
98
  const mode = raw?.mode === 'observe' ? 'observe' : 'enforce';
93
99
  const threshold = typeof raw?.threshold === 'number' && Number.isFinite(raw.threshold) && raw.threshold >= 0 && raw.threshold <= 1 ? raw.threshold : 0.3;
100
+ const batchMode = raw?.batchMode === 'single' || raw?.batchMode === 'split' ? raw.batchMode : 'auto';
94
101
  // An explicit array in settings (including empty) overrides the default set.
95
102
  const prefixes = Array.isArray(raw?.keepPrefixes)
96
103
  ? raw.keepPrefixes.filter(prefix => typeof prefix === 'string' && prefix)
@@ -100,7 +107,7 @@ export function createNarrowing({ evaluate, sessions, settings, coreTools = DEFA
100
107
  // never large enough to be rejected before it is sent.
101
108
  const configuredCap = Number.isSafeInteger(raw?.maxCandidates) && raw.maxCandidates >= 1 ? raw.maxCandidates : maxCandidates;
102
109
  const cap = Math.min(configuredCap, MAX_QUESTIONS);
103
- return { mode, threshold, prefixes, cap };
110
+ return { mode, threshold, prefixes, cap, batchMode };
104
111
  };
105
112
  const record = (turn, outcome, detail = {}) => {
106
113
  const id = turn?.agent?.session?.id;
@@ -111,12 +118,34 @@ export function createNarrowing({ evaluate, sessions, settings, coreTools = DEFA
111
118
  try { sessions.log(id, { kind: 'narrow', outcome, ...detail }); }
112
119
  catch { /* logging is best effort */ }
113
120
  };
121
+ // Send one relevance request per tool with bounded concurrency, then merge the
122
+ // per-tool answers into one result. Each request's prompt is only the task
123
+ // state plus a single question, so it cannot exceed a small-context backend's
124
+ // prompt limit. A tool whose request fails is omitted from the merged answers,
125
+ // which narrowTools treats as "keep" (best effort). Returns null only when
126
+ // every tool failed, so the caller can still report a backend error.
127
+ const evaluateSplit = async (state, tools, signal) => {
128
+ const answers = Object.create(null);
129
+ let anyOk = false;
130
+ for (let i = 0; i < tools.length; i += concurrency) {
131
+ const group = tools.slice(i, i + concurrency);
132
+ const settled = await Promise.all(group.map(async tool => {
133
+ try {
134
+ const reply = await evaluate(relevanceQuestions(state, [tool]), { signal });
135
+ const answer = reply?.answers?.[tool.name];
136
+ return isObject(answer) ? [tool.name, answer] : undefined;
137
+ } catch { return undefined; }
138
+ }));
139
+ for (const pair of settled) { if (pair) { answers[pair[0]] = pair[1]; anyOk = true; } }
140
+ }
141
+ return anyOk ? { model: 'split', answers } : null;
142
+ };
114
143
  const skip = { evaluated: false, applied: false, keep: [], drop: [], mode: 'observe' };
115
144
  return {
116
145
  async review(turn) {
117
146
  const tools = Array.isArray(turn?.tools) ? turn.tools.filter(tool => tool && typeof tool.name === 'string') : [];
118
147
  const names = tools.map(tool => tool.name);
119
- const { mode, threshold, prefixes, cap } = await resolveSettings();
148
+ const { mode, threshold, prefixes, cap, batchMode } = await resolveSettings();
120
149
  // A: core tools and keep-prefix matches are always kept and never sent to
121
150
  // the model for judging (e.g. mcp__openviking memory tools stay resident).
122
151
  const alwaysKeep = name => core.has(name) || prefixes.some(prefix => name.startsWith(prefix));
@@ -139,9 +168,29 @@ export function createNarrowing({ evaluate, sessions, settings, coreTools = DEFA
139
168
  const effectiveMode = overCap ? 'observe' : mode;
140
169
  const judged = overCap ? optional.slice(0, cap) : optional;
141
170
  const judgedNames = judged.map(tool => tool.name);
171
+ // Choose per-request strategy by backend context capacity. 'split' (or an
172
+ // 'auto' pass that already fell back) sends one request per tool so no
173
+ // prompt exceeds a small-context limit. 'single'/'auto' first try one
174
+ // whole-batch request; under 'auto', a context-overflow http-error flips
175
+ // this instance to split from then on and retries the same tools split.
142
176
  let result;
143
- try { result = await evaluate(relevanceQuestions(turn.state, judged), { signal: turn.signal }); }
144
- catch (error) { record(turn, 'error', { reason: typeof error?.reason === 'string' ? error.reason : 'unreachable', mode: effectiveMode }); return { ...skip, keep: names, mode: effectiveMode }; }
177
+ if (batchMode === 'split' || adaptiveSplit) {
178
+ result = await evaluateSplit(turn.state, judged, turn.signal);
179
+ if (!result) { record(turn, 'error', { reason: 'unreachable', mode: effectiveMode }); return { ...skip, keep: names, mode: effectiveMode }; }
180
+ } else {
181
+ try { result = await evaluate(relevanceQuestions(turn.state, judged), { signal: turn.signal }); }
182
+ catch (error) {
183
+ const reason = typeof error?.reason === 'string' ? error.reason : 'unreachable';
184
+ if (batchMode === 'auto' && reason === 'http-error') {
185
+ adaptiveSplit = true;
186
+ result = await evaluateSplit(turn.state, judged, turn.signal);
187
+ if (!result) { record(turn, 'error', { reason, mode: effectiveMode }); return { ...skip, keep: names, mode: effectiveMode }; }
188
+ } else {
189
+ record(turn, 'error', { reason, mode: effectiveMode });
190
+ return { ...skip, keep: names, mode: effectiveMode };
191
+ }
192
+ }
193
+ }
145
194
  const narrowed = narrowTools(judgedNames, result, { threshold });
146
195
  const keep = [...keptNames, ...narrowed.keep];
147
196
  const drop = narrowed.drop;
@@ -18,11 +18,65 @@ function safeTool(value) {
18
18
  return typeof value === 'string' && value.trim() ? value.trim().slice(0, 128) : undefined;
19
19
  }
20
20
 
21
- export function createSessionState({ maxSessions = 1024, maxLogEntries = 50, onLog } = {}) {
21
+ const toCount = value => (Number.isSafeInteger(value) && value >= 0 ? value : 0);
22
+
23
+ // Rebuild a trusted in-memory state from a persisted (untrusted) snapshot. Every
24
+ // counter is coerced into the emptyState() shape with a non-negative-integer
25
+ // guard and the trend severity into its enum, so a stale or tampered file can
26
+ // never inject an out-of-shape value into the live counters. The recent log is
27
+ // kept as plain records (newest-last); callers trim it to the log cap.
28
+ function coerceState(raw) {
29
+ const state = emptyState();
30
+ if (!raw || typeof raw !== 'object') return state;
31
+ if (typeof raw.enabled === 'boolean') state.enabled = raw.enabled;
32
+ state.attempts = toCount(raw.attempts);
33
+ state.failures = toCount(raw.failures);
34
+ const g = raw.gate;
35
+ if (g && typeof g === 'object') {
36
+ state.gate.attempts = toCount(g.attempts); state.gate.failures = toCount(g.failures);
37
+ state.gate.ask = toCount(g.ask); state.gate.deny = toCount(g.deny); state.gate.allow = toCount(g.allow);
38
+ const a = g.actual;
39
+ if (a && typeof a === 'object') { state.gate.actual.allow = toCount(a.allow); state.gate.actual.deny = toCount(a.deny); state.gate.actual.error = toCount(a.error); }
40
+ }
41
+ const c = raw.check;
42
+ if (c && typeof c === 'object') {
43
+ state.check.attempts = toCount(c.attempts); state.check.failures = toCount(c.failures); state.check.low = toCount(c.low);
44
+ state.check.run = toCount(c.run);
45
+ state.check.severity = ['normal', 'warn', 'severe'].includes(c.severity) ? c.severity : 'normal';
46
+ }
47
+ const n = raw.narrow;
48
+ if (n && typeof n === 'object') {
49
+ state.narrow.attempts = toCount(n.attempts); state.narrow.failures = toCount(n.failures);
50
+ state.narrow.applied = toCount(n.applied); state.narrow.dropped = toCount(n.dropped);
51
+ }
52
+ const k = raw.complete;
53
+ if (k && typeof k === 'object') {
54
+ state.complete.attempts = toCount(k.attempts); state.complete.failures = toCount(k.failures);
55
+ state.complete.unsatisfied = toCount(k.unsatisfied); state.complete.satisfied = toCount(k.satisfied);
56
+ state.complete.insufficient = toCount(k.insufficient); state.complete.steered = toCount(k.steered);
57
+ }
58
+ if (Array.isArray(raw.log)) {
59
+ state.log = raw.log
60
+ .filter(entry => entry && typeof entry === 'object' && !Array.isArray(entry) && typeof entry.kind === 'string')
61
+ .map(entry => ({ ...entry }));
62
+ }
63
+ return state;
64
+ }
65
+
66
+ export function createSessionState({ maxSessions = 1024, maxLogEntries = 50, onLog, loadState, persistState } = {}) {
22
67
  if (!Number.isSafeInteger(maxSessions) || maxSessions < 1) throw new Error('Invalid session limit');
23
68
  if (!Number.isSafeInteger(maxLogEntries) || maxLogEntries < 1) throw new Error('Invalid log limit');
24
69
  const sessions = new Map();
25
70
  const sink = typeof onLog === 'function' ? onLog : undefined;
71
+ const load = typeof loadState === 'function' ? loadState : undefined;
72
+ const persist = typeof persistState === 'function' ? persistState : undefined;
73
+ // Memoize rehydration per id so a session is seeded from disk at most once per
74
+ // process. Bounded like `sessions`; dropping a memo entry only risks a
75
+ // redundant disk read that no-ops (ensureLoaded never clobbers live state).
76
+ const loaded = new Map();
77
+ // Mirror the latest live state to the durable store after every mutation.
78
+ // Best-effort: a persistence fault must never surface in the decision path.
79
+ const bump = (key, state) => { if (persist) { try { persist(key, state); } catch { /* best effort */ } } };
26
80
  // FIFO eviction: when the map is full, drop the oldest-inserted session before
27
81
  // admitting a new one (Map preserves insertion order, so the first key is the
28
82
  // oldest). This mirrors loop-guard / narrowing and means the store never
@@ -40,9 +94,38 @@ export function createSessionState({ maxSessions = 1024, maxLogEntries = 50, onL
40
94
  return state;
41
95
  };
42
96
  return {
97
+ // Rehydrate a session's live counters/log from the durable store the first
98
+ // time it is touched this process, before any new event mutates it — so disk
99
+ // history and in-process events never double-count. Memoized per id; a no-op
100
+ // when no loadState was given or the session already has live state. Callers
101
+ // should await this before the first snapshot/record of a resumed session
102
+ // (the plugin does so at the turn's first step and in the panel routes).
103
+ async ensureLoaded(id) {
104
+ if (!load) return;
105
+ let key;
106
+ try { key = sessionKey(id); } catch { return; }
107
+ const existing = loaded.get(key);
108
+ if (existing) return existing;
109
+ const promise = (async () => {
110
+ if (sessions.has(key)) return; // live events already created state; keep it
111
+ let raw;
112
+ try { raw = await load(key); } catch { raw = undefined; }
113
+ if (!raw) return;
114
+ if (sessions.has(key)) return; // a concurrent mutation won the race; do not clobber
115
+ const state = coerceState(raw);
116
+ if (state.log.length > maxLogEntries) state.log.splice(0, state.log.length - maxLogEntries);
117
+ if (sessions.size >= maxSessions) sessions.delete(sessions.keys().next().value);
118
+ sessions.set(key, state);
119
+ })();
120
+ if (loaded.size >= maxSessions) loaded.delete(loaded.keys().next().value);
121
+ loaded.set(key, promise);
122
+ return promise;
123
+ },
43
124
  setEnabled(id, enabled) {
44
125
  if (typeof enabled !== 'boolean') throw new Error('Invalid enabled value');
45
- writable(id).enabled = enabled;
126
+ const state = writable(id);
127
+ state.enabled = enabled;
128
+ bump(sessionKey(id), state);
46
129
  },
47
130
  snapshot(id) {
48
131
  const stored = sessions.get(sessionKey(id));
@@ -62,26 +145,32 @@ export function createSessionState({ maxSessions = 1024, maxLogEntries = 50, onL
62
145
  state.gate.attempts++;
63
146
  if (outcome === 'error') { state.failures++; state.gate.failures++; }
64
147
  else state.gate[outcome]++;
148
+ bump(sessionKey(id), state);
65
149
  },
66
150
  recordActual(id, outcome) {
67
151
  if (!['allow', 'deny', 'error'].includes(outcome)) throw new Error('Invalid actual decision');
68
- writable(id).gate.actual[outcome]++;
152
+ const state = writable(id);
153
+ state.gate.actual[outcome]++;
154
+ bump(sessionKey(id), state);
69
155
  },
70
156
  recordCheck(id, outcome, trend) {
71
157
  if (!['ok', 'low', 'error'].includes(outcome)) throw new Error('Invalid self-check outcome');
72
158
  const state = writable(id);
73
159
  state.attempts++;
74
160
  state.check.attempts++;
75
- if (outcome === 'error') { state.failures++; state.check.failures++; return; }
76
- if (outcome === 'low') state.check.low++;
77
- // Advance the quality-trend run over this evaluated score. A good score
78
- // resets the run; a high-confidence low score grows it; a low-confidence
79
- // low score neither resets nor grows. `trend` carries the per-sample flags
80
- // and the configured thresholds; absent trend leaves the run unchanged.
81
- if (trend && typeof trend === 'object') {
82
- state.check.run = advanceRun(state.check.run, { lowScore: outcome === 'low', confident: trend.confident === true });
83
- state.check.severity = severityOf(state.check.run, { trendRun: trend.trendRun, trendSevereRun: trend.trendSevereRun });
161
+ if (outcome === 'error') { state.failures++; state.check.failures++; }
162
+ else {
163
+ if (outcome === 'low') state.check.low++;
164
+ // Advance the quality-trend run over this evaluated score. A good score
165
+ // resets the run; a high-confidence low score grows it; a low-confidence
166
+ // low score neither resets nor grows. `trend` carries the per-sample flags
167
+ // and the configured thresholds; absent trend leaves the run unchanged.
168
+ if (trend && typeof trend === 'object') {
169
+ state.check.run = advanceRun(state.check.run, { lowScore: outcome === 'low', confident: trend.confident === true });
170
+ state.check.severity = severityOf(state.check.run, { trendRun: trend.trendRun, trendSevereRun: trend.trendSevereRun });
171
+ }
84
172
  }
173
+ bump(sessionKey(id), state);
85
174
  },
86
175
  recordNarrow(id, outcome, dropped = 0) {
87
176
  if (!['ok', 'applied', 'error'].includes(outcome)) throw new Error('Invalid narrowing outcome');
@@ -93,6 +182,7 @@ export function createSessionState({ maxSessions = 1024, maxLogEntries = 50, onL
93
182
  state.narrow.applied++;
94
183
  if (Number.isSafeInteger(dropped) && dropped > 0) state.narrow.dropped += dropped;
95
184
  }
185
+ bump(sessionKey(id), state);
96
186
  },
97
187
  // Task-completion checking. `ok`/`unsatisfied` are real evaluations; `error`
98
188
  // is an unevaluated failure counted as a failure, never as "unsatisfied".
@@ -102,11 +192,14 @@ export function createSessionState({ maxSessions = 1024, maxLogEntries = 50, onL
102
192
  const state = writable(id);
103
193
  state.attempts++;
104
194
  state.complete.attempts++;
105
- if (outcome === 'error') { state.failures++; state.complete.failures++; return; }
106
- if (Number.isSafeInteger(detail.satisfied) && detail.satisfied > 0) state.complete.satisfied += detail.satisfied;
107
- if (Number.isSafeInteger(detail.unsatisfied) && detail.unsatisfied > 0) state.complete.unsatisfied += detail.unsatisfied;
108
- if (Number.isSafeInteger(detail.insufficient) && detail.insufficient > 0) state.complete.insufficient += detail.insufficient;
109
- if (detail.steered === true) state.complete.steered++;
195
+ if (outcome === 'error') { state.failures++; state.complete.failures++; }
196
+ else {
197
+ if (Number.isSafeInteger(detail.satisfied) && detail.satisfied > 0) state.complete.satisfied += detail.satisfied;
198
+ if (Number.isSafeInteger(detail.unsatisfied) && detail.unsatisfied > 0) state.complete.unsatisfied += detail.unsatisfied;
199
+ if (Number.isSafeInteger(detail.insufficient) && detail.insufficient > 0) state.complete.insufficient += detail.insufficient;
200
+ if (detail.steered === true) state.complete.steered++;
201
+ }
202
+ bump(sessionKey(id), state);
110
203
  },
111
204
  log(id, entry) {
112
205
  if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) throw new Error('Invalid log entry');
@@ -149,6 +242,7 @@ export function createSessionState({ maxSessions = 1024, maxLogEntries = 50, onL
149
242
  }
150
243
  try { sink(full); } catch { /* persistence is best effort */ }
151
244
  }
245
+ bump(sessionKey(id), state);
152
246
  },
153
247
  };
154
248
  }
@@ -0,0 +1,100 @@
1
+ import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+
6
+ export function stateDir() {
7
+ return join(homedir(), '.config', 'dsh-decision-layer', 'state');
8
+ }
9
+
10
+ // A session id is persisted only when it is safe as a single path segment, so a
11
+ // crafted id can never escape the state directory. dsh session ids are
12
+ // `session-<uuid>`, which pass; anything with separators, leading dot, `..`, or
13
+ // an unreasonable length is skipped (that session simply stays in-memory only).
14
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
15
+ export function safeStateId(id) {
16
+ return typeof id === 'string' && SAFE_ID.test(id) && !id.includes('..') ? id : undefined;
17
+ }
18
+
19
+ // Durable per-session mirror of the live decision counters + recent log. One
20
+ // small JSON file per session id (`<id>.json`), written debounced and atomically
21
+ // (unique tmp + rename), pruned by age on an occasional flush. This is separate
22
+ // from the JSONL research log: it exists only so a resumed session's live panel
23
+ // (dock count, metric cards, recent log) survives an instance restart instead of
24
+ // resetting to zero. All IO is best-effort — a failure never throws into the
25
+ // decision path; at worst the panel loses the last few seconds of counters.
26
+ export function createStateStore({ dir = stateDir(), flushIntervalMs = 2000,
27
+ retentionDays = 30, now = () => Date.now() } = {}) {
28
+ const pending = new Map(); // id -> latest live state reference awaiting a flush
29
+ let timer;
30
+ let flushing = false;
31
+ let lastPrune = 0;
32
+
33
+ const fileFor = id => join(dir, `${id}.json`);
34
+
35
+ const writeOne = async (id, state) => {
36
+ const temporary = join(dir, `${id}.${randomUUID()}.tmp`);
37
+ try {
38
+ await writeFile(temporary, `${JSON.stringify({ v: 1, at: now(), state })}\n`, { mode: 0o600, flag: 'wx' });
39
+ await rename(temporary, fileFor(id));
40
+ } finally {
41
+ await rm(temporary, { force: true }).catch(() => {});
42
+ }
43
+ };
44
+
45
+ const prune = async () => {
46
+ let names;
47
+ try { names = await readdir(dir); } catch { return; }
48
+ const cutoff = now() - retentionDays * 24 * 60 * 60 * 1000;
49
+ await Promise.all(names.map(async name => {
50
+ if (!name.endsWith('.json')) return;
51
+ try {
52
+ const info = await stat(join(dir, name));
53
+ if (info.mtimeMs < cutoff) await rm(join(dir, name), { force: true }).catch(() => {});
54
+ } catch { /* a file vanishing under us is fine */ }
55
+ }));
56
+ };
57
+
58
+ const flush = async () => {
59
+ if (flushing || pending.size === 0) return;
60
+ flushing = true;
61
+ // Snapshot ids now; each state is JSON.stringify'd at write time so the file
62
+ // reflects the latest counters, which is exactly what we want.
63
+ const batch = [...pending.entries()];
64
+ pending.clear();
65
+ try {
66
+ await mkdir(dir, { recursive: true, mode: 0o700 });
67
+ for (const [id, state] of batch) await writeOne(id, state).catch(() => {});
68
+ // Prune at most about once per hour of activity, not on every flush.
69
+ if (now() - lastPrune > 60 * 60 * 1000) { lastPrune = now(); await prune(); }
70
+ } catch { /* best effort; a dropped flush must never break the decision path */ }
71
+ finally { flushing = false; }
72
+ };
73
+
74
+ return {
75
+ // Read a session's persisted state, or undefined when there is no usable file.
76
+ async load(id) {
77
+ const safe = safeStateId(id);
78
+ if (!safe) return undefined;
79
+ try {
80
+ const parsed = JSON.parse(await readFile(fileFor(safe), 'utf8'));
81
+ if (parsed && typeof parsed === 'object' && parsed.state && typeof parsed.state === 'object' && !Array.isArray(parsed.state)) {
82
+ return parsed.state;
83
+ }
84
+ } catch { /* missing or malformed: no seed, start empty */ }
85
+ return undefined;
86
+ },
87
+ // Register the latest live state for a session and schedule a debounced flush.
88
+ save(id, state) {
89
+ const safe = safeStateId(id);
90
+ if (!safe || state === null || typeof state !== 'object') return;
91
+ pending.set(safe, state);
92
+ if (!timer) timer = setTimeout(() => { timer = undefined; void flush(); }, flushIntervalMs);
93
+ },
94
+ flush,
95
+ dispose() {
96
+ if (timer) { clearTimeout(timer); timer = undefined; }
97
+ return flush();
98
+ },
99
+ };
100
+ }