dsh-lean-router 1.1.0 → 2.1.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.
Files changed (155) hide show
  1. package/NOTICE.md +2 -4
  2. package/README.en.md +47 -43
  3. package/README.md +45 -41
  4. package/cordis.patch.yml +4 -26
  5. package/docs/adr/0001-token-ledger-durable-usage.md +11 -0
  6. package/docs/agents/domain.md +1 -1
  7. package/docs/architecture.en.md +51 -86
  8. package/docs/architecture.md +46 -77
  9. package/docs/changelog.en.md +41 -1
  10. package/docs/changelog.md +41 -1
  11. package/docs/configuration.en.md +25 -56
  12. package/docs/configuration.md +14 -45
  13. package/docs/install.en.md +2 -2
  14. package/docs/install.md +2 -2
  15. package/docs/quickstart.en.md +29 -34
  16. package/docs/quickstart.md +11 -16
  17. package/docs/release-checklist.en.md +3 -4
  18. package/docs/release-checklist.md +5 -6
  19. package/docs//350/267/257/347/224/261-/350/256/276/350/256/241/350/257/264/346/230/216.md +2 -2
  20. package/lib/bands.js +4 -2
  21. package/lib/index.js +9 -61
  22. package/lib/router.js +15 -148
  23. package/lib/token-ledger/index.js +147 -0
  24. package/lib/token-ledger/live.js +184 -0
  25. package/package.json +5 -14
  26. package/presets/base/frag-lean.patch.yml +1 -5
  27. package/presets/base/frag-preset.patch.yml +1 -3
  28. package/presets/base/frag-router.patch.yml +1 -12
  29. package/presets/base/frag-toolface.patch.yml +0 -2
  30. package/presets/base/lean-router.patch.yml +1 -4
  31. package/scripts/doctor.mjs +15 -10
  32. package/test/integration-preset.test.mjs +4 -3
  33. package/test/plugin-entry.test.mjs +15 -50
  34. package/test/router-bands.test.mjs +26 -0
  35. package/test/router.test.mjs +7 -47
  36. package/test/token-ledger-live.test.mjs +351 -0
  37. package/test/token-ledger.test.mjs +264 -0
  38. package/assets/gating.weights.json +0 -13
  39. package/assets/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  40. package/assets/skills/ask-matt/SKILL.md +0 -80
  41. package/assets/skills/ask-matt/agents/openai.yaml +0 -5
  42. package/assets/skills/chief-of-staff/SKILL.md +0 -76
  43. package/assets/skills/chief-of-staff/agents/openai.yaml +0 -5
  44. package/assets/skills/code-review/SKILL.md +0 -91
  45. package/assets/skills/code-review/agents/openai.yaml +0 -5
  46. package/assets/skills/codebase-design/DEEPENING.md +0 -37
  47. package/assets/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  48. package/assets/skills/codebase-design/SKILL.md +0 -116
  49. package/assets/skills/codebase-design/agents/openai.yaml +0 -5
  50. package/assets/skills/diagnosing-bugs/SKILL.md +0 -140
  51. package/assets/skills/diagnosing-bugs/agents/openai.yaml +0 -5
  52. package/assets/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  53. package/assets/skills/domain-modeling/ADR-FORMAT.md +0 -47
  54. package/assets/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  55. package/assets/skills/domain-modeling/SKILL.md +0 -76
  56. package/assets/skills/domain-modeling/agents/openai.yaml +0 -5
  57. package/assets/skills/grilling/SKILL.md +0 -52
  58. package/assets/skills/grilling/agents/openai.yaml +0 -5
  59. package/assets/skills/handoff/SKILL.md +0 -17
  60. package/assets/skills/handoff/agents/openai.yaml +0 -5
  61. package/assets/skills/implement/SKILL.md +0 -55
  62. package/assets/skills/implement/agents/openai.yaml +0 -5
  63. package/assets/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  64. package/assets/skills/improve-codebase-architecture/SKILL.md +0 -72
  65. package/assets/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  66. package/assets/skills/loop-me/SKILL.md +0 -33
  67. package/assets/skills/loop-me/agents/openai.yaml +0 -5
  68. package/assets/skills/pr/CREDITS.md +0 -3
  69. package/assets/skills/pr/SKILL.md +0 -172
  70. package/assets/skills/pr/agents/openai.yaml +0 -5
  71. package/assets/skills/prototype/LOGIC.md +0 -67
  72. package/assets/skills/prototype/SKILL.md +0 -28
  73. package/assets/skills/prototype/UI.md +0 -112
  74. package/assets/skills/prototype/agents/openai.yaml +0 -5
  75. package/assets/skills/research/SKILL.md +0 -14
  76. package/assets/skills/research/agents/openai.yaml +0 -5
  77. package/assets/skills/retro/SKILL.md +0 -45
  78. package/assets/skills/retro/agents/openai.yaml +0 -5
  79. package/assets/skills/setup-matt-pocock-skills/SKILL.md +0 -121
  80. package/assets/skills/setup-matt-pocock-skills/agents/openai.yaml +0 -5
  81. package/assets/skills/setup-matt-pocock-skills/domain.md +0 -51
  82. package/assets/skills/setup-matt-pocock-skills/issue-tracker-github.md +0 -50
  83. package/assets/skills/setup-matt-pocock-skills/issue-tracker-gitlab.md +0 -46
  84. package/assets/skills/setup-matt-pocock-skills/issue-tracker-local.md +0 -30
  85. package/assets/skills/setup-matt-pocock-skills/triage-labels.md +0 -15
  86. package/assets/skills/setup-ts-deep-modules/SKILL.md +0 -103
  87. package/assets/skills/setup-ts-deep-modules/agents/openai.yaml +0 -5
  88. package/assets/skills/setup-ts-deep-modules/dependency-cruiser.config.cjs +0 -95
  89. package/assets/skills/software-factory/EXAMPLE-TASKS.md +0 -80
  90. package/assets/skills/software-factory/GIT-HOSTS.md +0 -84
  91. package/assets/skills/software-factory/OBSERVABILITY-PLATFORMS.md +0 -75
  92. package/assets/skills/software-factory/RUNNERS.md +0 -94
  93. package/assets/skills/software-factory/SKILL.md +0 -99
  94. package/assets/skills/software-factory/TICKET-TRACKERS.md +0 -85
  95. package/assets/skills/tdd/SKILL.md +0 -40
  96. package/assets/skills/tdd/agents/openai.yaml +0 -5
  97. package/assets/skills/tdd/mocking.md +0 -59
  98. package/assets/skills/tdd/tests.md +0 -77
  99. package/assets/skills/teach/GLOSSARY-FORMAT.md +0 -35
  100. package/assets/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  101. package/assets/skills/teach/MISSION-FORMAT.md +0 -31
  102. package/assets/skills/teach/RESOURCES-FORMAT.md +0 -32
  103. package/assets/skills/teach/SKILL.md +0 -141
  104. package/assets/skills/teach/agents/openai.yaml +0 -5
  105. package/assets/skills/to-questionnaire/SKILL.md +0 -55
  106. package/assets/skills/to-questionnaire/agents/openai.yaml +0 -5
  107. package/assets/skills/to-spec/SKILL.md +0 -76
  108. package/assets/skills/to-spec/agents/openai.yaml +0 -5
  109. package/assets/skills/to-tickets/SKILL.md +0 -106
  110. package/assets/skills/to-tickets/agents/openai.yaml +0 -5
  111. package/assets/skills/triage/AGENT-BRIEF.md +0 -207
  112. package/assets/skills/triage/OUT-OF-SCOPE.md +0 -105
  113. package/assets/skills/triage/SKILL.md +0 -113
  114. package/assets/skills/triage/agents/openai.yaml +0 -5
  115. package/assets/skills/wait-what/SKILL.md +0 -8
  116. package/assets/skills/wait-what/agents/openai.yaml +0 -5
  117. package/assets/skills/wayfinder/SKILL.md +0 -129
  118. package/assets/skills/wayfinder/agents/openai.yaml +0 -5
  119. package/assets/skills/wizard/SKILL.md +0 -46
  120. package/assets/skills/wizard/agents/openai.yaml +0 -5
  121. package/assets/skills/wizard/template.sh +0 -223
  122. package/assets/skills/writing-beats/SKILL.md +0 -44
  123. package/assets/skills/writing-beats/agents/openai.yaml +0 -5
  124. package/assets/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  125. package/assets/skills/writing-for-agents/SKILL.md +0 -83
  126. package/assets/skills/writing-for-agents/agents/openai.yaml +0 -5
  127. package/assets/skills/writing-fragments/SKILL.md +0 -80
  128. package/assets/skills/writing-fragments/agents/openai.yaml +0 -5
  129. package/assets/skills/writing-shape/SKILL.md +0 -59
  130. package/assets/skills/writing-shape/agents/openai.yaml +0 -5
  131. package/assets/skills.matrix.json +0 -311
  132. package/docs/HANDOFF-2026-11-22.md +0 -155
  133. package/docs/matrix.en.md +0 -57
  134. package/docs/matrix.md +0 -57
  135. package/docs//346/212/200/350/203/275/351/227/250/346/216/247-/350/256/276/350/256/241/350/257/264/346/230/216.md +0 -134
  136. package/docs//351/235/242/346/235/277-/350/256/276/350/256/241/350/257/264/346/230/216.md +0 -205
  137. package/lib/audit-commands.js +0 -289
  138. package/lib/audit-sink.js +0 -137
  139. package/lib/client.js +0 -203
  140. package/lib/gate-runner.js +0 -179
  141. package/lib/skill-provider.js +0 -167
  142. package/lib/skillgate.js +0 -396
  143. package/lib/skills-panel.js +0 -322
  144. package/scripts/check-drift.mjs +0 -24
  145. package/skills.manifest.json +0 -287
  146. package/test/audit-commands.test.mjs +0 -325
  147. package/test/audit-sink.test.mjs +0 -150
  148. package/test/client-plugin.test.mjs +0 -117
  149. package/test/gate-run.test.mjs +0 -173
  150. package/test/manifest.test.mjs +0 -25
  151. package/test/provider.test.mjs +0 -21
  152. package/test/skillgate-provider.test.mjs +0 -122
  153. package/test/skillgate.test.mjs +0 -217
  154. package/test/skills-panel.test.mjs +0 -114
  155. package/ui/go.json +0 -19
@@ -1,289 +0,0 @@
1
- // dsh-lean-router - 审计命令与命中统计(票 07)
2
- //
3
- // /lean-audit 的实现本体(lib/router.js 命令分发处加法接线注册;handler 可测试直调)。
4
- // 数据源 = 审计 JSONL 回放(lib/audit-sink.js 的 readAuditEntries),不新增内存态
5
- // (约束台账 1:来源 = 审计流回放)。落盘路径与权重文件路径由接线方注入(context)。
6
- //
7
- // 输出四要素(与 ui/go.json 面板按钮同源):
8
- // 决策行 —— 最近 N 条 skillgate-round 的单行摘要(turn/band/auto/hint/tokens)
9
- // 得分表折叠 —— 默认只展开最新一条的 Top5;/lean-audit scores [N] 展开全量得分行
10
- // token 对比 —— 最新决策 estTokens / budgetTokens(charsPerToken 注明)
11
- // 黄条 —— 超预算 / 有软降级 / 回放坏行 / 权重回退时输出 ⚠ 告警段,否则不出现
12
- //
13
- // 纯 node 可测;本模块不写文件、不改 invocation。
14
-
15
- import { readAuditEntries, defaultAuditPath } from "./audit-sink.js";
16
- import { loadGateWeights } from "./skillgate.js";
17
-
18
- /** 默认显示的最近决策条数(/lean-audit [N] 可改,1..100)。 */
19
- export const DEFAULT_RECENT = 10;
20
- /** 得分表折叠视图默认展开的 Top 行数。 */
21
- export const SCORE_TABLE_TOP = 5;
22
- /** 统计回放单文件条数上限(防异常大文件;轮转已把当前文件压在 5MB)。 */
23
- export const REPLAY_MAX_ENTRIES = 2000;
24
-
25
- const VIEWS = ["scores", "stats", "weights"];
26
-
27
- /** 解析 /lean-audit 参数:[scores|stats|weights] [N](纯数字 = summary 的条数)。 */
28
- export function parseAuditArgs(raw) {
29
- const tokens = typeof raw === "string" ? raw.trim().split(/[ \t]+/).filter(Boolean) : [];
30
- let view = "summary";
31
- let count = null;
32
- let rest = tokens;
33
- if (tokens.length > 0 && VIEWS.includes(tokens[0])) {
34
- view = tokens[0];
35
- rest = tokens.slice(1);
36
- }
37
- if (rest.length > 0) {
38
- const joined = rest.join(" ");
39
- if (!/^\d+$/.test(joined)) throw new Error("usage: /lean-audit [scores|stats|weights] [N]");
40
- count = parseInt(joined, 10);
41
- }
42
- if (view === "scores" && count === null) count = 1;
43
- if (view === "summary" && count === null) count = DEFAULT_RECENT;
44
- if (count !== null && (count < 1 || count > 100)) throw new Error("/lean-audit N must be 1..100");
45
- return { view, count };
46
- }
47
-
48
- /** 决策行(决策要素):#序 turn band auto/hint tokens;complex 加 * 标记。 */
49
- export function formatDecisionLine(entry, index) {
50
- const d = entry.decision ?? {};
51
- const num = String(index).padStart(2, "0");
52
- const band = (d.band ?? "?") + (entry.task?.complex === true ? "*" : "");
53
- return (
54
- "#" + num +
55
- " turn=" + String(entry.turn ?? "-") +
56
- " band=" + band +
57
- " auto=" + (Array.isArray(d.auto) ? d.auto.length : 0) +
58
- " hint=" + (Array.isArray(d.hint) ? d.hint.length : 0) +
59
- " tokens=" + (d.estTokens ?? "?") + "/" + (d.budgetTokens ?? "?")
60
- );
61
- }
62
-
63
- /** token 对比行(最新一条);无条目返回 null。 */
64
- export function formatTokenLine(entry) {
65
- const d = entry?.decision;
66
- if (!d) return null;
67
- const cpt = entry.config?.charsPerToken ?? 4;
68
- return (
69
- "Token (turn " + String(entry.turn ?? "-") + "): est " + (d.estTokens ?? "?") +
70
- " / budget " + (d.budgetTokens ?? "?") + " tokens (charsPerToken=" + cpt + ")" +
71
- (d.estTokens > d.budgetTokens ? " OVER" : " within")
72
- );
73
- }
74
-
75
- /** 得分行归一:一条审计的 scores -> 展示行(档位来自 decision)。 */
76
- export function scoreRows(entry) {
77
- const auto = new Set(Array.isArray(entry?.decision?.auto) ? entry.decision.auto : []);
78
- const hint = new Set(Array.isArray(entry?.decision?.hint) ? entry.decision.hint : []);
79
- return (Array.isArray(entry?.scores) ? entry.scores : []).map((s) => ({
80
- name: s?.name ?? "?",
81
- score: typeof s?.score === "number" ? s.score : 0,
82
- tier: auto.has(s?.name) ? "auto" : hint.has(s?.name) ? "hint" : "off",
83
- scene: s?.signals?.category?.scene ?? "process",
84
- keywords: Array.isArray(s?.signals?.keywords) ? s.signals.keywords : [],
85
- model: s?.model === true,
86
- user: s?.user === true,
87
- points: s?.signals?.category?.points ?? 0,
88
- complex: s?.signals?.category?.complex === true,
89
- }));
90
- }
91
-
92
- function padEnd(text, width) {
93
- const s = String(text);
94
- return s.length >= width ? s : s + " ".repeat(width - s.length);
95
- }
96
- function padStart(text, width) {
97
- const s = String(text);
98
- return s.length >= width ? s : " ".repeat(width - s.length) + s;
99
- }
100
-
101
- /** 全量得分表文本(展开视图;按分数降序、名字序次之)。 */
102
- export function renderScoreTable(entry) {
103
- const rows = scoreRows(entry).sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
104
- const lines = [];
105
- lines.push(
106
- "Score table turn=" + String(entry?.turn ?? "-") + " band=" + (entry?.decision?.band ?? "?") +
107
- " (" + rows.length + " skills):"
108
- );
109
- lines.push(padEnd("skill", 20) + padStart("score", 6) + " " + padEnd("tier", 6) + padEnd("scene", 12) + padEnd("kw", 14) + "m/u");
110
- for (const r of rows) {
111
- lines.push(
112
- padEnd(r.name, 20) + padStart(r.score, 6) + " " +
113
- padEnd(r.tier, 6) + padEnd(r.scene, 12) +
114
- padEnd(r.keywords.length === 0 ? "-" : r.keywords.join(","), 14) +
115
- (r.model ? "m" : "-") + (r.user ? "u" : "-")
116
- );
117
- }
118
- return lines.join("\n");
119
- }
120
-
121
- /** 折叠视图:Top K 行摘要 + 展开提示。 */
122
- export function renderScoreCollapsed(entry) {
123
- const rows = scoreRows(entry).sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
124
- const total = rows.length;
125
- const top = rows.slice(0, SCORE_TABLE_TOP);
126
- const lines = ["Score table (collapsed, top " + top.length + " of " + total + "; /lean-audit scores to expand):"];
127
- for (const r of top) {
128
- lines.push(" " + padEnd(r.name, 20) + padStart(r.score, 3) + " " + r.tier);
129
- }
130
- return lines.join("\n");
131
- }
132
-
133
- /** 命中统计:按技能×场景聚合(约束台账 1),纯函数、只吃回放条目。 */
134
- export function aggregateStats(entries) {
135
- const rows = new Map();
136
- for (const entry of entries) {
137
- if (!entry || entry.kind !== "skillgate-round" || !Array.isArray(entry.scores)) continue;
138
- const autoSet = new Set(Array.isArray(entry.decision?.auto) ? entry.decision.auto : []);
139
- const hintSet = new Set(Array.isArray(entry.decision?.hint) ? entry.decision.hint : []);
140
- const degraded = Array.isArray(entry.decision?.degradations) ? entry.decision.degradations : [];
141
- for (const s of entry.scores) {
142
- if (typeof s?.name !== "string") continue;
143
- let row = rows.get(s.name);
144
- if (!row) {
145
- row = { name: s.name, scene: s?.signals?.category?.scene ?? "process", rounds: 0, hits: 0, auto: 0, hint: 0, degraded: 0 };
146
- rows.set(s.name, row);
147
- }
148
- row.rounds += 1;
149
- if (Array.isArray(s?.signals?.keywords) && s.signals.keywords.length > 0) row.hits += 1;
150
- if (autoSet.has(s.name)) row.auto += 1;
151
- if (hintSet.has(s.name)) row.hint += 1;
152
- if (degraded.some((d) => d?.name === s.name)) row.degraded += 1;
153
- }
154
- }
155
- return [...rows.values()].sort(
156
- (a, b) => (b.hits + b.auto + b.hint) - (a.hits + a.auto + a.hint) || a.name.localeCompare(b.name)
157
- );
158
- }
159
-
160
- /** 命中统计表文本。 */
161
- export function renderStatsTable(rows, rounds) {
162
- const lines = [];
163
- lines.push("Hit stats (per skill x scene, from " + rounds + " replayed round(s)):");
164
- lines.push(
165
- padEnd("skill", 20) + padEnd("scene", 12) +
166
- padStart("rounds", 7) + padStart("hits", 6) + padStart("auto", 6) + padStart("hint", 6) + padStart("degraded", 9)
167
- );
168
- for (const r of rows) {
169
- lines.push(
170
- padEnd(r.name, 20) + padEnd(r.scene, 12) +
171
- padStart(r.rounds, 7) + padStart(r.hits, 6) + padStart(r.auto, 6) + padStart(r.hint, 6) + padStart(r.degraded, 9)
172
- );
173
- }
174
- return lines.join("\n");
175
- }
176
-
177
- /** 黄条:超预算 / 软降级 / 回放坏行 / 权重回退;仅在有问题时返回行(无则无黄条)。 */
178
- export function collectWarnings(entries, replay, weights) {
179
- const bars = [];
180
- for (const e of entries) {
181
- const d = e.decision;
182
- if (!d) continue;
183
- if (d.estTokens > d.budgetTokens) {
184
- bars.push("⚠ turn " + String(e.turn ?? "?") + ": token est " + d.estTokens + " > budget " + d.budgetTokens);
185
- }
186
- const dg = Array.isArray(d.degradations) ? d.degradations.length : 0;
187
- if (dg > 0) bars.push("⚠ turn " + String(e.turn ?? "?") + ": " + dg + " skill(s) soft-degraded to hint");
188
- }
189
- if (replay && replay.skipped > 0) {
190
- bars.push("⚠ replay skipped " + replay.skipped + " malformed line(s)");
191
- }
192
- if (weights && weights.error) {
193
- bars.push("⚠ weights " + weights.status + ": " + weights.error + " (defaults in effect)");
194
- }
195
- return bars;
196
- }
197
-
198
- function renderBanner(bars) {
199
- return bars.length === 0 ? "" : bars.join("\n") + "\n";
200
- }
201
-
202
- /** 手动权重展示(/lean-audit weights)。 */
203
- export function renderWeights(weights) {
204
- const c = weights.config;
205
- const lines = [];
206
- lines.push("Gate weights [" + weights.status + "] - source: " + weights.source);
207
- if (weights.error) lines.push("error: " + weights.error);
208
- lines.push(
209
- "autoScore=" + c.autoScore + " hintScore=" + c.hintScore +
210
- " tokenBudget=" + c.tokenBudget + " charsPerToken=" + c.charsPerToken +
211
- " maxTaskTextChars=" + c.maxTaskTextChars
212
- );
213
- for (const band of ["react", "spec", "weak"]) {
214
- const m = Object.entries(c.sceneMap[band] ?? {}).map(([k, v]) => k + "=" + v).join(" ") || "(none)";
215
- lines.push("sceneMap." + band + ": " + m);
216
- }
217
- lines.push("complexBoost: " + (Object.entries(c.complexBoost).map(([k, v]) => k + "=" + v).join(" ") || "(none)"));
218
- lines.push("arbitration: " + c.arbitration.map((r) => r.scene + "->" + r.prefer).join(", "));
219
- lines.push("Edit assets/gating.weights.json (gateConfig subset; scene bonus / thresholds / soft-degrade line).");
220
- lines.push("Missing or invalid file falls back to the hardcoded defaults; weights never change invocation.");
221
- return lines.join("\n");
222
- }
223
-
224
- function emptyStateText(auditPath) {
225
- return (
226
- "No audit entries yet at " + auditPath + "\n" +
227
- "The audit file appears once the gate wiring runs (master integration): skillgate round -> getAuditChannel -> wireAuditSink.\n" +
228
- "See docs/面板-设计说明.md for the wiring."
229
- );
230
- }
231
-
232
- /** 汇总视图(默认):黄条 -> 决策行 -> token 对比 -> 得分表折叠 -> 命中统计。 */
233
- export function renderSummaryView(entries, count, replay, auditPath) {
234
- if (entries.length === 0) return emptyStateText(auditPath);
235
- const recent = entries.slice(-count);
236
- const bars = collectWarnings(recent, replay, null);
237
- const lines = [];
238
- const banner = renderBanner(bars);
239
- if (banner) lines.push(banner.trimEnd());
240
- lines.push("Lean audit - replayed from " + auditPath + " (" + entries.length + " round(s) in file, showing last " + recent.length + ")");
241
- lines.push("Decisions (newest last):");
242
- for (let i = 0; i < recent.length; i += 1) lines.push(formatDecisionLine(recent[i], i + 1));
243
- const token = formatTokenLine(entries[entries.length - 1]);
244
- if (token) lines.push(token);
245
- lines.push(renderScoreCollapsed(entries[entries.length - 1]));
246
- lines.push(renderStatsTable(aggregateStats(entries), entries.length));
247
- return lines.join("\n");
248
- }
249
-
250
- /** 得分表展开视图:最近 N 条的全量得分行。 */
251
- export function renderScoresView(entries, count, auditPath) {
252
- if (entries.length === 0) return emptyStateText(auditPath ?? "<audit path>");
253
- const recent = entries.slice(-count);
254
- return recent.map((e) => renderScoreTable(e)).join("\n\n");
255
- }
256
-
257
- /** 统计视图:黄条 -> 命中统计表。 */
258
- export function renderStatsView(entries, replay, auditPath) {
259
- if (entries.length === 0) return emptyStateText(auditPath ?? "<audit path>");
260
- const bars = collectWarnings([], replay, null);
261
- const lines = [];
262
- const banner = renderBanner(bars);
263
- if (banner) lines.push(banner.trimEnd());
264
- lines.push(renderStatsTable(aggregateStats(entries), entries.length));
265
- return lines.join("\n");
266
- }
267
-
268
- /**
269
- * /lean-audit handler 的共享实现(lib/router.js 注册;测试直调)。
270
- * context: { auditPath?, weightsPath? };无 agent 依赖(审计是全局流)。
271
- */
272
- export async function executeAuditCommand(invocation, context) {
273
- const auditPath = context?.auditPath ?? defaultAuditPathSafe();
274
- const weightsPath = context?.weightsPath ?? null;
275
- try {
276
- const { view, count } = parseAuditArgs(invocation?.rawInput ?? "");
277
- if (view === "weights") {
278
- const weights = await loadGateWeights(weightsPath ?? undefined);
279
- return { kind: "success", text: renderWeights(weights) };
280
- }
281
- const replay = readAuditEntries(auditPath, { limit: REPLAY_MAX_ENTRIES });
282
- const entries = replay.entries.filter((e) => e && e.kind === "skillgate-round");
283
- if (view === "stats") return { kind: "success", text: renderStatsView(entries, replay, auditPath) };
284
- if (view === "scores") return { kind: "success", text: renderScoresView(entries, count ?? 1, auditPath) };
285
- return { kind: "success", text: renderSummaryView(entries, count ?? DEFAULT_RECENT, replay, auditPath) };
286
- } catch (error) {
287
- return { kind: "error", text: "Audit command failed: " + (error instanceof Error ? error.message : String(error)) };
288
- }
289
- }
package/lib/audit-sink.js DELETED
@@ -1,137 +0,0 @@
1
- // dsh-lean-router - 审计落盘 sink(票 07)
2
- //
3
- // 结论先行:审计通道(lib/skillgate.js createAuditChannel)默认只在内存环形缓冲
4
- // + 订阅;本模块把决策流接成 JSONL 文件——追加写、5MB 轮转、目录懒建、错误全吞
5
- // (审计永不破坏门控管线)。默认路径 <homedir>/.dsh/lean-router/audit.jsonl,
6
- // 经 patch 行 config.auditPath 可配(接线由 master 集成,见 docs/面板-设计说明.md)。
7
- //
8
- // 纯 node 可测(node:fs/node:os/node:path 内建);每条决策一行 JSON(v=1 格式,
9
- // 含通道盖章的 seq);轮转单代:audit.jsonl -> audit.jsonl.1(覆盖旧 .1)。
10
- // 回放(面板数据源 = 面板读文件)只读当前文件,轮转历史不并入(口径见设计说明)。
11
-
12
- import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";
13
- import { dirname, join } from "node:path";
14
- import { homedir } from "node:os";
15
-
16
- /** 默认轮转阈值:5MB(约束台账:追加写、5MB 轮转)。 */
17
- export const DEFAULT_AUDIT_MAX_BYTES = 5 * 1024 * 1024;
18
-
19
- /** 默认落盘路径:<homedir>/.dsh/lean-router/audit.jsonl(patch 行 config.auditPath 可配)。 */
20
- export function defaultAuditPath() {
21
- return join(homedir(), ".dsh", "lean-router", "audit.jsonl");
22
- }
23
-
24
- function normalizeOptions(options) {
25
- const path =
26
- typeof options?.path === "string" && options.path.length > 0
27
- ? options.path
28
- : defaultAuditPath();
29
- const maxBytes =
30
- typeof options?.maxBytes === "number" && Number.isSafeInteger(options.maxBytes) && options.maxBytes > 0
31
- ? options.maxBytes
32
- : DEFAULT_AUDIT_MAX_BYTES;
33
- return { path, maxBytes };
34
- }
35
-
36
- /**
37
- * 审计 sink:订阅函数形态(channel.subscribe(sink.entry) 兼容)+ 回放读取。
38
- * 写失败只计数不抛错(门控管线安全);目录懒建;当前文件达到 maxBytes 先轮转再写。
39
- */
40
- export function createAuditSink(options) {
41
- const { path, maxBytes } = normalizeOptions(options);
42
- const stats = { lines: 0, bytes: 0, rotations: 0, errors: 0 };
43
- let dirReady = false;
44
-
45
- function ensureDir() {
46
- if (dirReady) return;
47
- mkdirSync(dirname(path), { recursive: true });
48
- dirReady = true;
49
- }
50
-
51
- function rotateIfNeeded() {
52
- let size = 0;
53
- try {
54
- size = statSync(path).size;
55
- } catch {
56
- return; // 文件尚不存在:无需轮转
57
- }
58
- if (size < maxBytes) return;
59
- try {
60
- renameSync(path, path + ".1");
61
- stats.rotations += 1;
62
- dirReady = true;
63
- } catch {
64
- // rename 失败(Windows 占用等):放弃本轮轮转,继续追加(审计不中断)。
65
- }
66
- }
67
-
68
- function entry(stamped) {
69
- let line;
70
- try {
71
- line = JSON.stringify(stamped);
72
- } catch {
73
- stats.errors += 1;
74
- return;
75
- }
76
- if (typeof line !== "string") {
77
- stats.errors += 1;
78
- return;
79
- }
80
- try {
81
- ensureDir();
82
- rotateIfNeeded();
83
- appendFileSync(path, line + "\n", "utf8");
84
- stats.lines += 1;
85
- stats.bytes += Buffer.byteLength(line + "\n", "utf8");
86
- } catch {
87
- stats.errors += 1;
88
- dirReady = false; // 目录可能被外移:下次写入重试懒建
89
- }
90
- }
91
-
92
- return {
93
- entry,
94
- path,
95
- maxBytes,
96
- stats: () => ({ ...stats }),
97
- };
98
- }
99
-
100
- /** 把 sink 接上审计通道(加法接线);返回 { sink, unsubscribe }。 */
101
- export function wireAuditSink(channel, options) {
102
- const sink = createAuditSink(options);
103
- const unsubscribe = channel.subscribe(sink.entry);
104
- return { sink, unsubscribe };
105
- }
106
-
107
- /**
108
- * 回放(审计流回放的数据源):读 JSONL 为条目数组,容忍坏行(跳过并计数)。
109
- * limit 取最新的 N 条(文件尾部向头部);轮转文件(*.1)不并入回放。
110
- */
111
- export function readAuditEntries(path, options) {
112
- const limit =
113
- typeof options?.limit === "number" && Number.isSafeInteger(options.limit) && options.limit > 0
114
- ? options.limit
115
- : Infinity;
116
- let text;
117
- try {
118
- text = readFileSync(path, "utf8");
119
- } catch (error) {
120
- if (error && error.code === "ENOENT") return { entries: [], skipped: 0, missing: true };
121
- return { entries: [], skipped: 0, missing: false, error: String(error?.message ?? error) };
122
- }
123
- const lines = text.split("\n");
124
- const out = [];
125
- let skipped = 0;
126
- for (let i = lines.length - 1; i >= 0 && out.length < limit; i -= 1) {
127
- const raw = lines[i];
128
- if (raw.trim().length === 0) continue;
129
- try {
130
- out.push(JSON.parse(raw));
131
- } catch {
132
- skipped += 1;
133
- }
134
- }
135
- out.reverse();
136
- return { entries: out, skipped, missing: false };
137
- }
package/lib/client.js DELETED
@@ -1,203 +0,0 @@
1
- // dsh-lean-router - 客户端 UI 层(技能面板 · 右侧栏标签页)
2
- //
3
- // 形态(用户拍板):右侧栏 tab,不做浮层、不往 document.body 追加第二份应用。
4
- // 契约来源:已安装真机范例 @modusensus/dsh-mneme 的 lib/client.js 与 dsh-cost-meter。
5
- // 1) 类型与引导挂服务 sidebarRightTabs: tabs.register({ id, kind, title, guide })
6
- // 2) 正文与标题挂 slot: sidebar.right.pane.tab / sidebar.right.pane.tab.title,
7
- // spec 用 { name, key: TAB_ID, inject }(注意是 key 不是 id)
8
- // 3) 打开: ctx.get("sidebarRight").openTab(TAB_KIND)
9
- //
10
- // 踩过的坑(别再犯):
11
- // - 直接读 ctx.register 会抛 cannot get property "register" without inject(1.0.6)
12
- // - apply 早于 slots 服务就绪,ctx.get("slots") 是 undefined(1.0.7)
13
- // 所以一律用 ctx.inject(["slots"], cb) 等服务就绪后再注册。
14
- // - 面板不要渲染在顶栏 slot 内(会被祖先 transform/overflow 裁成黑条,1.0.9)
15
- //
16
- // 加载契约:package.json 的 dsh.client.platform="web" + exports["./client"],
17
- // 入口形如 window.__ModuleLoader__.load({ id, factory }),factory(require) 取宿主模块。
18
- window.__ModuleLoader__.load({
19
- id: "dsh-lean-router",
20
- factory: (require) => {
21
- const React = require("react");
22
- const h = React.createElement;
23
-
24
- const TAB_ID = "lean-router.skills";
25
- const TAB_KIND = "lean-router-skills";
26
- const TAB_TITLE = "技能";
27
-
28
- const btnStyle = {
29
- display: "inline-flex",
30
- alignItems: "center",
31
- gap: 4,
32
- height: 26,
33
- padding: "0 10px",
34
- marginLeft: 6,
35
- borderRadius: 6,
36
- border: "1px solid var(--dsh-border, rgba(128,128,128,.35))",
37
- background: "transparent",
38
- color: "inherit",
39
- fontSize: 12,
40
- lineHeight: "24px",
41
- cursor: "pointer",
42
- };
43
-
44
- /** 右栏标签图标:三条横线,取 currentColor 跟随宿主主题。 */
45
- function SkillsIcon(props) {
46
- const size = props && props.size ? props.size : 16;
47
- return h(
48
- "svg",
49
- { width: size, height: size, viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true" },
50
- h("path", {
51
- d: "M3 4h10M3 8h10M3 12h6",
52
- stroke: "currentColor",
53
- strokeWidth: 1.5,
54
- strokeLinecap: "round",
55
- })
56
- );
57
- }
58
-
59
- /** 右栏正文(1.0.10 只做壳,验证形态)。样式全部继承宿主主题,不写死颜色。 */
60
- function SkillsPane() {
61
- return h(
62
- "div",
63
- { style: { padding: "12px 14px", fontSize: 13, lineHeight: 1.7 } },
64
- h("div", { style: { fontWeight: 600, marginBottom: 6 } }, "技能面板 · 骨架"),
65
- h(
66
- "div",
67
- { style: { opacity: 0.75 } },
68
- "右栏形态已接好:这是 lean-router 的右侧栏标签页,可以和其他右栏面板并存。"
69
- ),
70
- h(
71
- "div",
72
- { style: { opacity: 0.75, marginTop: 6 } },
73
- "下一步接入 31 个技能、开关与命中统计。"
74
- )
75
- );
76
- }
77
-
78
- /** 顶栏「技能」按钮:打开右栏标签(宿主无右栏服务时什么也不做,只告警)。 */
79
- function SkillsButton(props) {
80
- const open = props && typeof props.open === "function" ? props.open : () => {};
81
- return h(
82
- "button",
83
- { type: "button", style: btnStyle, title: "打开技能面板(右侧栏)", onClick: open },
84
- "技能"
85
- );
86
- }
87
-
88
- /** 打开右栏标签;返回是否打开成功。 */
89
- function makeOpener(ctx) {
90
- return () => {
91
- try {
92
- const sidebar = typeof ctx.get === "function" ? ctx.get("sidebarRight") : undefined;
93
- if (sidebar && typeof sidebar.openTab === "function") {
94
- sidebar.openTab(TAB_KIND);
95
- return true;
96
- }
97
- console.warn("[lean-router] sidebarRight.openTab 不可用,右栏无法打开");
98
- } catch (err) {
99
- console.warn("[lean-router] sidebarRight.openTab failed", err);
100
- }
101
- return false;
102
- };
103
- }
104
-
105
- function apply(ctx) {
106
- const disposers = [];
107
-
108
- const registerSlots = (scope) => {
109
- const slots = scope && typeof scope.get === "function" ? scope.get("slots") : undefined;
110
- if (!slots || typeof slots.inject !== "function" || typeof slots.register !== "function") {
111
- return false;
112
- }
113
-
114
- // 1) 右栏 tab 的类型与引导入口。类型挂在宿主服务上、插件重挂时仍留着,
115
- // 所以必须先查重,否则宿主会抛 tab type id already registered。
116
- try {
117
- const tabs = typeof scope.get === "function" ? scope.get("sidebarRightTabs") : undefined;
118
- if (tabs && typeof tabs.register === "function") {
119
- const already = typeof tabs.get === "function" ? tabs.get(TAB_ID) : null;
120
- if (!already) {
121
- tabs.register({
122
- id: TAB_ID,
123
- kind: TAB_KIND,
124
- title: () => TAB_TITLE,
125
- guide: [
126
- {
127
- id: "lean-router:skills:guide",
128
- order: 60,
129
- title: () => TAB_TITLE,
130
- description: () => "技能清单、开关与命中统计",
131
- icon: (size) => h(SkillsIcon, { size }),
132
- },
133
- ],
134
- });
135
- }
136
- }
137
- } catch (err) {
138
- console.warn("[lean-router] sidebarRightTabs.register failed", err);
139
- }
140
-
141
- // 2) 顶栏入口 + 右栏正文与标题。opener 必须基于已就绪的 scope,
142
- // 用外层 ctx 取 sidebarRight 可能还拿不到(1.0.8 同款时机问题)。
143
- const open = makeOpener(scope);
144
- const registrations = [
145
- [
146
- "conversation.session.header.actions",
147
- () => ({ name: "conversation.session.header.actions", id: "lean-router.skills", order: 60, inject: () => ({ open }) }),
148
- SkillsButton,
149
- ],
150
- [
151
- "sidebar.right.pane.tab",
152
- () => ({
153
- name: "sidebar.right.pane.tab",
154
- key: TAB_ID,
155
- inject: (sessionId) => ({ sessionId }),
156
- }),
157
- SkillsPane,
158
- ],
159
- [
160
- "sidebar.right.pane.tab.title",
161
- () => ({ name: "sidebar.right.pane.tab.title", key: TAB_ID }),
162
- () => TAB_TITLE,
163
- ],
164
- ];
165
-
166
- let registered = 0;
167
- for (const [slot, spec, component] of registrations) {
168
- try {
169
- const dispose = slots.inject(slot, () => slots.register(spec(), component));
170
- if (typeof dispose === "function") disposers.push(dispose);
171
- registered += 1;
172
- } catch (err) {
173
- console.warn("[lean-router] register failed on", slot, err);
174
- }
175
- }
176
- return registered > 0;
177
- };
178
-
179
- if (typeof ctx.inject === "function") {
180
- try {
181
- const dispose = ctx.inject(["slots"], (scoped) => {
182
- registerSlots(scoped);
183
- });
184
- if (typeof dispose === "function") disposers.push(dispose);
185
- } catch (err) {
186
- console.warn("[lean-router] ctx.inject(['slots']) failed", err);
187
- }
188
- } else {
189
- registerSlots(ctx);
190
- }
191
-
192
- return () => {
193
- for (const d of disposers) {
194
- try {
195
- d();
196
- } catch {}
197
- }
198
- };
199
- }
200
-
201
- return { apply };
202
- },
203
- });