@linxin666/dsh-liangshen 0.4.8 → 0.4.9

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 (35) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +10 -8
  3. package/README.zh.md +10 -8
  4. package/lib/client.js +87 -54
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +9 -1
  7. package/lib/types/client/PluginSettingsCard.d.ts +21 -0
  8. package/package.json +15 -15
  9. package/presets/liangshen/agent.cordis.yml +76 -18
  10. package/presets/liangshen/dispatcher-rules.mjs +128 -47
  11. package/presets/liangshen/fact-ledger.mjs +14 -0
  12. package/presets/liangshen/subagent-routes.mjs +396 -0
  13. package/presets/liangshen/tool-catalog.mjs +7 -4
  14. package/src/client/PluginSettingsCard.tsx +78 -18
  15. package/src/client/settings-card.module.css +71 -10
  16. package/src/composition.test.ts +20 -0
  17. package/src/composition.ts +10 -2
  18. package/tools/benchmark-live-run.mjs +116 -14
  19. package/tools/benchmark-report.mjs +44 -0
  20. package/tools/check-dispatcher-rules.mjs +130 -0
  21. package/tools/probe-selftest.mjs +130 -0
  22. package/tools/probes/budget-ledger/env.mjs +103 -0
  23. package/tools/probes/budget-ledger/grade.mjs +31 -0
  24. package/tools/probes/budget-ledger/strategies.mjs +25 -0
  25. package/tools/probes/oncall-backlog/env.mjs +141 -0
  26. package/tools/probes/oncall-backlog/grade.mjs +28 -0
  27. package/tools/probes/oncall-backlog/strategies.mjs +37 -0
  28. package/tools/probes/prior-override/env.mjs +153 -0
  29. package/tools/probes/prior-override/grade.mjs +31 -0
  30. package/tools/probes/prior-override/strategies.mjs +30 -0
  31. package/tools/probes/refresh-quota/env.mjs +140 -0
  32. package/tools/probes/refresh-quota/grade.mjs +30 -0
  33. package/tools/probes/refresh-quota/strategies.mjs +29 -0
  34. package/tools/probes/shared.mjs +75 -0
  35. package/tools/tasks/liangshen-v41-probes.json +59 -0
@@ -5,9 +5,19 @@
5
5
  * as siblings of the built-in Shell / Agent loop / Web search cards. */
6
6
 
7
7
  .card {
8
+ /* The card's local scale: every literal below reads one of these, and the
9
+ nested density overrides the same seven on the same element, so one rule
10
+ set serves both densities. */
11
+ --settings-card-radius: 12px;
12
+ --settings-card-header-pad: 16px;
13
+ --settings-card-header-gap: 13px;
14
+ --settings-card-title-size: 15px;
15
+ --settings-card-description-size: 13px;
16
+ --settings-card-body-inset: 16px;
17
+ --settings-card-motion: 0.18s;
8
18
  border: 1px solid var(--dsw-alias-border-l2);
9
19
  background: var(--dsw-alias-bg-layer-3);
10
- border-radius: 12px;
20
+ border-radius: var(--settings-card-radius);
11
21
  list-style: none;
12
22
  transition: border-color 0.16s, background 0.16s;
13
23
  }
@@ -21,6 +31,24 @@
21
31
  border-color: var(--dsw-alias-label-dimmed);
22
32
  }
23
33
 
34
+ /* Nested density: a topic card inside another card's body. It overrides the
35
+ local scale only, so the first-level card and this one stay one rule set. */
36
+ .cardNested {
37
+ --settings-card-radius: 10px;
38
+ --settings-card-header-pad: 10px 12px;
39
+ --settings-card-header-gap: 10px;
40
+ --settings-card-title-size: 13px;
41
+ --settings-card-description-size: 12px;
42
+ --settings-card-body-inset: 12px;
43
+ }
44
+
45
+ /* One line: the header already carries the full sentence on its title. */
46
+ .cardNested .description {
47
+ white-space: nowrap;
48
+ overflow: hidden;
49
+ text-overflow: ellipsis;
50
+ }
51
+
24
52
  .header {
25
53
  appearance: none;
26
54
  width: 100%;
@@ -34,10 +62,10 @@
34
62
  cursor: pointer;
35
63
  background: transparent;
36
64
  border: 0;
37
- border-radius: 12px;
65
+ border-radius: var(--settings-card-radius);
38
66
  align-items: center;
39
- gap: 13px;
40
- padding: 16px;
67
+ gap: var(--settings-card-header-gap);
68
+ padding: var(--settings-card-header-pad);
41
69
  display: flex;
42
70
  }
43
71
 
@@ -49,10 +77,10 @@
49
77
  .headerStatic {
50
78
  width: 100%;
51
79
  box-sizing: border-box;
52
- border-radius: 12px;
80
+ border-radius: var(--settings-card-radius);
53
81
  align-items: center;
54
- gap: 13px;
55
- padding: 16px;
82
+ gap: var(--settings-card-header-gap);
83
+ padding: var(--settings-card-header-pad);
56
84
  display: flex;
57
85
  }
58
86
 
@@ -85,7 +113,7 @@
85
113
 
86
114
  .name {
87
115
  color: var(--dsw-alias-label-primary);
88
- font-size: 15px;
116
+ font-size: var(--settings-card-title-size);
89
117
  font-weight: 600;
90
118
  line-height: 1.4;
91
119
  }
@@ -95,7 +123,7 @@
95
123
  print leave 12-13px hint text below readable contrast (orca-link #778399
96
124
  on cream measures ~3.4:1). */
97
125
  color: var(--dsw-alias-label-secondary);
98
- font-size: 13px;
126
+ font-size: var(--settings-card-description-size);
99
127
  line-height: 1.5;
100
128
  }
101
129
 
@@ -135,9 +163,36 @@
135
163
  transform: rotate(180deg);
136
164
  }
137
165
 
166
+ /* Body disclosure. One transition pair drives both legs: the wrapper
167
+ animates 0fr -> 1fr and back, the body is its only item and shrinks into the
168
+ collapsed track. Only the moving states clip, so a settled card never cuts
169
+ off a field's popup. */
170
+ .disclosure {
171
+ display: grid;
172
+ grid-template-rows: 0fr;
173
+ opacity: 0;
174
+ transition: grid-template-rows var(--settings-card-motion) ease, opacity var(--settings-card-motion) ease;
175
+ }
176
+
177
+ .disclosure[data-state='collapsed'],
178
+ .disclosure[data-state='entering'],
179
+ .disclosure[data-state='closing'] {
180
+ overflow: hidden;
181
+ }
182
+
183
+ .disclosure[data-state='entering'],
184
+ .disclosure[data-state='shown'] {
185
+ grid-template-rows: 1fr;
186
+ opacity: 1;
187
+ }
188
+
189
+ .disclosure > .body {
190
+ min-height: 0;
191
+ }
192
+
138
193
  .body {
139
194
  border-top: 1px solid var(--dsw-alias-border-l2);
140
- margin: 0 16px;
195
+ margin: 0 var(--settings-card-body-inset);
141
196
  padding-bottom: 8px;
142
197
  }
143
198
 
@@ -510,4 +565,10 @@
510
565
  .toggleThumb {
511
566
  transition: none;
512
567
  }
568
+
569
+ /* Reduced motion drops the height travel but keeps the fade, so a closing
570
+ body still leaves through the leg its own state started. */
571
+ .disclosure {
572
+ transition-property: opacity;
573
+ }
513
574
  }
@@ -275,6 +275,26 @@ describe('applyPresetOverrides', () => {
275
275
  expect(configOf(rowOf(applied, 'minimal-prompt'))['dispatcher']).toBe(false)
276
276
  })
277
277
 
278
+ it('operator gets the wire from the catalog row this preset declares', () => {
279
+ // Given the 0.2.1 API, where a preset selects its wire through
280
+ // agent.ctx.tools.presentAs, When the operator commits a presentation, Then
281
+ // the tool-catalog row carries it and nothing else is written: the
282
+ // declaration and the catalog text read one value.
283
+ const ptc = applyPresetOverrides(rows(), { presentation: 'ptc' })
284
+ expect(configOf(rowOf(ptc, 'tool-catalog'))['presentation']).toBe('ptc')
285
+ const native = applyPresetOverrides(rows(), { presentation: 'native' })
286
+ expect(configOf(rowOf(native, 'tool-catalog'))['presentation']).toBe('native')
287
+ expect(rowOf(native, 'tool-catalog').disabled).toBeUndefined()
288
+ })
289
+
290
+ it('operator keeps the shipped ptc wire when no presentation is committed', () => {
291
+ // Given no committed presentation, When the overlay is applied, Then the
292
+ // catalog row keeps the value the composition ships: the shipped default is
293
+ // the collapsed wire, and an absent setting never rewrites it.
294
+ const applied = applyPresetOverrides(rows(), {})
295
+ expect(configOf(rowOf(applied, 'tool-catalog'))['presentation']).toBe('ptc')
296
+ })
297
+
278
298
  it('operator is never given a row the composition does not carry', () => {
279
299
  // Given a composition with no tool-catalog row, When the operator applies
280
300
  // a presentation choice, Then no row is invented for it.
@@ -500,10 +500,18 @@ export interface PresetOverrides {
500
500
  dispatcher?: boolean
501
501
  }
502
502
 
503
- /** One settings overlay entry: the row it targets and the keys it writes. */
503
+ /** One settings overlay entry: the row it targets and the config keys it writes. */
504
504
  type OverrideTarget = readonly [string, Readonly<Record<string, unknown>>]
505
505
 
506
- /** The overlay table: settings field to composition row and config key. */
506
+ /**
507
+ * The overlay table: settings field to composition row and config key.
508
+ *
509
+ * `presentation` writes the `tool-catalog` row alone, because that row's
510
+ * declaration IS the wire: the plugin hands the value to
511
+ * `agent.ctx.tools.presentAs` and re-assembles, so the catalog text and the
512
+ * declared presentation always travel together. The composition carries no
513
+ * executor row to mount or unmount.
514
+ */
507
515
  function overrideTargets(overrides: PresetOverrides): OverrideTarget[] {
508
516
  return [
509
517
  ['tool-catalog', { ...overrides.presentation === undefined ? {} : { presentation: overrides.presentation } }],
@@ -41,7 +41,7 @@ import { createHash } from 'node:crypto'
41
41
  import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
42
42
  import { createRequire } from 'node:module'
43
43
  import { tmpdir } from 'node:os'
44
- import { dirname, join, relative, resolve, sep } from 'node:path'
44
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path'
45
45
  import { fileURLToPath, pathToFileURL } from 'node:url'
46
46
 
47
47
  const HERE = dirname(fileURLToPath(import.meta.url))
@@ -53,6 +53,24 @@ const require = createRequire(import.meta.url)
53
53
  /** Fixed route every variant runs on, so the comparison isolates the preset. */
54
54
  export const FIXED_ROUTE = { provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: 'max' }
55
55
 
56
+ /**
57
+ * Parse 'provider/model[/reasoning-effort]' into a route. The default stays
58
+ * FIXED_ROUTE so an aggregated comparison reads one route per report; a probe
59
+ * run may instead name the route the operator actually uses, which is the
60
+ * only way its behaviour says anything about that operator's sessions.
61
+ */
62
+ export function parseRoute(spec) {
63
+ const parts = String(spec).split('/')
64
+ if (parts.length < 2 || parts[0] === '' || parts[1] === '') {
65
+ throw new Error('benchmark: --route wants provider/model[/reasoning-effort]')
66
+ }
67
+ return {
68
+ provider: parts[0],
69
+ model: parts[1],
70
+ reasoningEffort: parts[2] !== undefined && parts[2] !== '' ? parts[2] : FIXED_ROUTE.reasoningEffort,
71
+ }
72
+ }
73
+
56
74
  /** The two turns the protocol smoke check uses: an anchored exploration, then a promoted mutation. */
57
75
  export const DEFAULT_TURNS = [
58
76
  'List the files in the current directory with the shell, then reply DONE and stop.',
@@ -595,10 +613,24 @@ export function loadTaskFile(path) {
595
613
  if (!Array.isArray(parsed?.tasks) || parsed.tasks.length === 0) {
596
614
  throw new Error(`benchmark: ${path} carries no tasks array`)
597
615
  }
616
+ const base = dirname(resolve(path))
598
617
  for (const task of parsed.tasks) {
599
618
  if (typeof task?.id !== 'string' || !Array.isArray(task?.turns) || typeof task?.check !== 'string') {
600
619
  throw new Error(`benchmark: task ${JSON.stringify(task?.id)} needs an id, turns, and a check`)
601
620
  }
621
+ // A task seeds either inline files or a directory (and support files) that
622
+ // already lives in the repository: a behaviour probe is a small program,
623
+ // and inlining it into JSON would make it unreadable and unreviewable.
624
+ if (task.from !== undefined) {
625
+ const list = Array.isArray(task.from) ? task.from : [task.from]
626
+ if (list.some((entry) => typeof entry !== 'string' || entry === '')) {
627
+ throw new Error(`benchmark: task ${JSON.stringify(task.id)} has a from entry that is not a path`)
628
+ }
629
+ Object.defineProperty(task, '__fromPaths', {
630
+ value: list.map((entry) => resolve(base, entry)),
631
+ enumerable: false,
632
+ })
633
+ }
602
634
  }
603
635
  return parsed
604
636
  }
@@ -623,6 +655,48 @@ function writeTaskFiles(workspace, files) {
623
655
  }
624
656
  }
625
657
 
658
+ /**
659
+ * Seed a task workspace: its inline files first, then every `from` path. A
660
+ * directory is copied by its contents, a file by its name, so a probe's
661
+ * simulator and the shared module it imports land side by side.
662
+ */
663
+ export function materializeTask(workspace, task) {
664
+ writeTaskFiles(workspace, task.files)
665
+ for (const source of task.__fromPaths ?? []) {
666
+ const info = statSync(source, { throwIfNoEntry: false })
667
+ if (info === undefined) {
668
+ throw new Error(`benchmark: task ${JSON.stringify(task.id)} from ${source} does not exist`)
669
+ }
670
+ if (info.isDirectory()) cpSync(source, workspace, { recursive: true })
671
+ else cpSync(source, join(workspace, basename(source)))
672
+ }
673
+ }
674
+
675
+ /**
676
+ * Read a probe's behavioural numbers: the same program shape as a check, but
677
+ * it prints one JSON object and is allowed to fail while still reporting.
678
+ */
679
+ export async function evaluateMetrics(workspace, metrics, timeoutMs = 60000) {
680
+ const result = await spawnCaptured(
681
+ process.execPath,
682
+ ['--input-type=module', '-e', metrics],
683
+ { cwd: workspace },
684
+ timeoutMs,
685
+ )
686
+ const lines = result.stdout.split('\n').map((line) => line.trim()).filter((line) => line !== '')
687
+ const last = lines.at(-1)
688
+ if (last === undefined) return { error: 'metrics produced no output' }
689
+ try {
690
+ const parsed = JSON.parse(last)
691
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
692
+ return { error: 'metrics must print one JSON object' }
693
+ }
694
+ return parsed
695
+ } catch {
696
+ return { error: 'metrics output was not JSON: ' + last.slice(0, 120) }
697
+ }
698
+ }
699
+
626
700
  /**
627
701
  * Run one task's acceptance check in the workspace. The check is a Node module
628
702
  * body, so a task never depends on a platform shell's quoting rules.
@@ -701,15 +775,26 @@ export function priceRun(usage, prices, route) {
701
775
  }
702
776
 
703
777
  /** Build the variant patch that redirects persistence and selects the isolated preset. */
704
- export function buildPatch({ variantId, variant, presetDir, runDir, turns }) {
778
+ export function buildPatch({ variantId, variant, presetDir, runDir, turns, route = FIXED_ROUTE }) {
705
779
  const presetId = variant.official === true ? OFFICIAL_PRESET_ID : variantId
706
780
  const lines = [
707
- '- id: headless-startup',
708
- ' disabled: true',
709
- '',
781
+ '# The startup row stays MOUNTED: it publishes the headlessStartup provider',
782
+ '# that sandbox-policy and the agent-plane rows inject, and disabling it (as',
783
+ '# this runner did before DSH 0.2.1) leaves every dependent row waiting for a',
784
+ '# service that can no longer appear, so the preset never mounts. Only the',
785
+ '# runner row is disabled: it is what would execute the task itself, and this',
786
+ '# patch replaces it with the benchmark driver below.',
710
787
  '- id: headless-runner',
711
788
  ' disabled: true',
712
789
  '',
790
+ '# DSH 0.2.1 disables the managed credential store in the headless bundle,',
791
+ '# which turns every request into an immediate authentication failure and',
792
+ '# records a session that never reached a model. This run resolves',
793
+ '# credentials the way an interactive session does, so the row is re-enabled',
794
+ '# here rather than replaced.',
795
+ '- id: credentials',
796
+ ' disabled: false',
797
+ '',
713
798
  '- id: session-persistence-jsonl',
714
799
  ' config:',
715
800
  ` root: ${JSON.stringify(join(runDir, 'sessions').replace(/\\/g, '/'))}`,
@@ -717,9 +802,9 @@ export function buildPatch({ variantId, variant, presetDir, runDir, turns }) {
717
802
  '',
718
803
  '- id: agent-default-model',
719
804
  ' config:',
720
- ` provider: ${FIXED_ROUTE.provider}`,
721
- ` model: ${FIXED_ROUTE.model}`,
722
- ` reasoningEffort: ${FIXED_ROUTE.reasoningEffort}`,
805
+ ' provider: ' + route.provider,
806
+ ' model: ' + route.model,
807
+ ' reasoningEffort: ' + (route.reasoningEffort ?? FIXED_ROUTE.reasoningEffort),
723
808
  '',
724
809
  '# The preset roster. The headless profile mounts neither the registry nor a',
725
810
  '# preset, so the variant supplies both: `default` names the evaluated preset',
@@ -793,10 +878,11 @@ export async function runLiveCase(options) {
793
878
 
794
879
  const workspace = join(runDir, 'workspace')
795
880
  mkdirSync(workspace, { recursive: true })
796
- if (options.task !== undefined) writeTaskFiles(workspace, options.task.files)
881
+ if (options.task !== undefined) materializeTask(workspace, options.task)
797
882
 
883
+ const route = options.route ?? FIXED_ROUTE
798
884
  const turns = options.turns ?? options.task?.turns ?? DEFAULT_TURNS
799
- const patch = buildPatch({ variantId, variant, presetDir, runDir, turns })
885
+ const patch = buildPatch({ variantId, variant, presetDir, runDir, turns, route })
800
886
 
801
887
  const patchPath = join(runDir, 'variant.patch.yml')
802
888
  writeFileSync(patchPath, patch, 'utf8')
@@ -830,6 +916,11 @@ export async function runLiveCase(options) {
830
916
  const check = options.task === undefined
831
917
  ? undefined
832
918
  : await evaluateCheck(workspace, options.task.check, options.timeoutMs ?? 120000)
919
+ // The behavioural numbers ride beside the pass/fail verdict: a probe can
920
+ // pass on the score while the habit it exists to expose is still there.
921
+ const behaviour = options.task?.metrics === undefined
922
+ ? null
923
+ : await evaluateMetrics(workspace, options.task.metrics)
833
924
 
834
925
  return {
835
926
  variant: variantId,
@@ -846,6 +937,8 @@ export async function runLiveCase(options) {
846
937
  timedOut: child.timedOut,
847
938
  passed: check === undefined ? null : check.passed === true && child.code === 0 && !child.timedOut,
848
939
  check,
940
+ behaviour,
941
+ route,
849
942
  durationMs: Date.now() - started,
850
943
  outcome,
851
944
  stderrTail: child.stderr.split('\n').filter((line) => line.trim() !== '').slice(-12).join('\n'),
@@ -894,8 +987,9 @@ export async function runLiveSuite(options) {
894
987
  const timeoutMs = options.timeoutMs ?? 300000
895
988
  const prices = resolvePriceTable(options.prices) ?? null
896
989
 
897
- const routeKey = routePriceKey(FIXED_ROUTE)
898
- const routePrice = routePrices(prices, FIXED_ROUTE)
990
+ const route = options.route ?? FIXED_ROUTE
991
+ const routeKey = routePriceKey(route)
992
+ const routePrice = routePrices(prices, route)
899
993
  // A budget gate that cannot price a run would silently never trigger, which is
900
994
  // exactly the unbounded spend the plan forbids; validate instead of pretending.
901
995
  if (routePrice !== undefined) assertPriceEntry(routePrice, routeKey)
@@ -908,6 +1002,7 @@ export async function runLiveSuite(options) {
908
1002
 
909
1003
  const baseline = await collectBaseline()
910
1004
  baseline.taskRevision = taskRevision(corpus)
1005
+ baseline.route = route
911
1006
  baseline.suite = {
912
1007
  groups,
913
1008
  repeat,
@@ -937,10 +1032,11 @@ export async function runLiveSuite(options) {
937
1032
  turns: task.turns,
938
1033
  repetition,
939
1034
  timeoutMs,
1035
+ route,
940
1036
  keep: options.keep === true,
941
1037
  })
942
1038
  sessions += 1
943
- const costCny = priceRun(run.usage, prices, FIXED_ROUTE)
1039
+ const costCny = priceRun(run.usage, prices, route)
944
1040
  if (costCny !== null) estimatedCostCny += costCny
945
1041
  const record = { baseline, costCny, ...run }
946
1042
  const file = join(outDir, 'live-' + group + '-' + task.id + '-r' + repetition + '.json')
@@ -973,11 +1069,17 @@ if (isMain) {
973
1069
  const outDir = read('--out', '.benchmark-results')
974
1070
  const timeoutMs = Number(read('--timeout', '300000'))
975
1071
 
1072
+ const routeSpec = read('--route', undefined)
1073
+ // Named apart from the per-run 'route' read further down, which is the route
1074
+ // a run actually reported rather than the one it was asked for.
1075
+ const selectedRoute = routeSpec === undefined ? FIXED_ROUTE : parseRoute(routeSpec)
1076
+
976
1077
  if (args.includes('--tasks')) {
977
1078
  const corpus = loadTaskFile(read('--tasks'))
978
1079
  const pricesPath = read('--prices', undefined)
979
1080
  const suite = await runLiveSuite({
980
1081
  tasks: corpus,
1082
+ route: selectedRoute,
981
1083
  groups: read('--groups', undefined)?.split(',').map((entry) => entry.trim()).filter(Boolean),
982
1084
  repeat: Number(read('--repeat', '3')),
983
1085
  maxSessions: Number(read('--max-sessions', '0')) > 0 ? Number(read('--max-sessions', '0')) : Number.POSITIVE_INFINITY,
@@ -991,7 +1093,7 @@ if (isMain) {
991
1093
  console.log(`aggregate with: node tools/benchmark-report.mjs ${outDir}`)
992
1094
  } else {
993
1095
  const variant = read('--variant', 'B')
994
- const report = await runLiveCase({ variant, timeoutMs, keep: args.includes('--keep') })
1096
+ const report = await runLiveCase({ variant, timeoutMs, route: selectedRoute, keep: args.includes('--keep') })
995
1097
  mkdirSync(outDir, { recursive: true })
996
1098
  const outFile = join(outDir, `live-${variant}.json`)
997
1099
  writeFileSync(outFile, JSON.stringify({ baseline: await collectBaseline(), ...report }, null, 2))
@@ -88,6 +88,30 @@ function costOf(entries) {
88
88
  return priced === 0 ? null : total
89
89
  }
90
90
 
91
+ /**
92
+ * Per-group means of the behavioural numbers a probe task reports. These are
93
+ * not outcome measures: a probe passes or fails on its oracle, and these
94
+ * numbers say which habit produced that outcome. They are kept apart from the
95
+ * success rate on purpose, because the whole point of a probe is that the two
96
+ * can disagree.
97
+ */
98
+ export function aggregateBehaviour(entries) {
99
+ const sums = new Map()
100
+ const counts = new Map()
101
+ for (const entry of entries) {
102
+ const behaviour = entry?.behaviour
103
+ if (behaviour === null || typeof behaviour !== 'object' || Array.isArray(behaviour)) continue
104
+ for (const [key, value] of Object.entries(behaviour)) {
105
+ if (typeof value !== 'number' || !Number.isFinite(value)) continue
106
+ sums.set(key, (sums.get(key) ?? 0) + value)
107
+ counts.set(key, (counts.get(key) ?? 0) + 1)
108
+ }
109
+ }
110
+ const out = {}
111
+ for (const [key, sum] of sums) out[key] = { mean: sum / counts.get(key), n: counts.get(key) }
112
+ return out
113
+ }
114
+
91
115
  /** Per-group descriptive statistics over the raw run records. */
92
116
  export function aggregateGroups(runs) {
93
117
  const byGroup = new Map()
@@ -127,6 +151,7 @@ export function aggregateGroups(runs) {
127
151
  humanInterventions: sumOf(entries, (run) => run.humanInterventions),
128
152
  approvalAsks: sumOf(entries, (run) => run.approvalsAsked),
129
153
  estimatedCostCny: costOf(entries),
154
+ behaviour: aggregateBehaviour(graded),
130
155
  }
131
156
  }
132
157
  return groups
@@ -316,6 +341,24 @@ export function renderMarkdown(report) {
316
341
  ].join(' | ') + ' |')
317
342
  }
318
343
  lines.push('')
344
+ const metricNames = [...new Set(Object.values(report.groups)
345
+ .flatMap((stats) => Object.keys(stats.behaviour ?? {})))].sort()
346
+ if (metricNames.length > 0) {
347
+ lines.push('## Behaviour metrics (probe tasks, per-group mean)')
348
+ lines.push('')
349
+ lines.push('| Meta metric | ' + GROUP_ORDER.filter((group) => report.groups[group] !== undefined).join(' | ') + ' |')
350
+ lines.push('| --- |' + GROUP_ORDER.filter((group) => report.groups[group] !== undefined).map(() => ' --- |').join(''))
351
+ for (const metric of metricNames) {
352
+ const cells = GROUP_ORDER
353
+ .filter((group) => report.groups[group] !== undefined)
354
+ .map((group) => {
355
+ const value = report.groups[group].behaviour?.[metric]
356
+ return value === undefined ? 'n/a' : value.mean.toFixed(2) + ' (n=' + value.n + ')'
357
+ })
358
+ lines.push('| ' + metric + ' | ' + cells.join(' | ') + ' |')
359
+ }
360
+ lines.push('')
361
+ }
319
362
  lines.push('## Paired comparisons')
320
363
  lines.push('')
321
364
  lines.push('| Comparison | Purpose | Tasks paired | Mean delta (95% CI) |')
@@ -346,6 +389,7 @@ export function renderMarkdown(report) {
346
389
  lines.push('- Model tool errors exclude transport failures: a run that cannot reach a host is evidence about the network, not about the model, so the two are reported side by side.')
347
390
  lines.push('- Cost is the price book currency (CNY), not USD: the route bills in CNY and the published row is quoted per million CNY.')
348
391
  lines.push('- Language-style counters (we and let me) stay with tools/analyze-session.mjs, which needs reasoning text the durable log does not always carry; those counters are not part of the outcome measures here.')
392
+ lines.push('- A probe task carries its own oracle under tools/probes: the pass column is that oracle, and the behaviour table is the habit that produced it. A probe that cannot separate its own scripted good and bad policies fails tools/probe-selftest.mjs, so a probe reading here has been shown to discriminate before any model ran it.')
349
393
  lines.push('- A small sample screens a direction; it does not claim a stable improvement. Widen the sample within the stated budget before concluding.')
350
394
  lines.push('')
351
395
  return lines.join('\n')
@@ -0,0 +1,130 @@
1
+ /**
2
+ * check-dispatcher-rules -- does the block this preset ships still match the
3
+ * lineage it was extracted from?
4
+ *
5
+ * The block is maintained here, so nothing forces it to move when the origin
6
+ * package moves. This script is the signal: it reads the installed origin
7
+ * package's dispatch preset, normalizes both texts, and reports the sentences
8
+ * that differ. It never edits anything and it never guesses: when the package
9
+ * is absent, or its layout is not the one this script knows, it says so and
10
+ * exits without failing, because absence is not evidence of drift.
11
+ *
12
+ * Exit codes
13
+ * 0 no drift, or nothing to compare against
14
+ * 3 drift found
15
+ * 4 the package is absent (only with --strict)
16
+ *
17
+ * Usage: node tools/check-dispatcher-rules.mjs [--strict] [--verbose]
18
+ */
19
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
20
+ import { createRequire } from 'node:module'
21
+ import { dirname, join } from 'node:path'
22
+
23
+ import { DISPATCHER_RULES, DISPATCHER_RULES_PROVENANCE } from '../presets/liangshen/dispatcher-rules.mjs'
24
+
25
+ const require = createRequire(import.meta.url)
26
+ const ORIGIN = DISPATCHER_RULES_PROVENANCE.package
27
+
28
+ /** The installed origin package's root, or undefined when it is not installed. */
29
+ export function originRoot() {
30
+ try {
31
+ return dirname(require.resolve(ORIGIN + '/package.json'))
32
+ } catch {
33
+ return undefined
34
+ }
35
+ }
36
+
37
+ /** Find the dispatch preset file by content rather than by an assumed path. */
38
+ export function originPresetFile(root) {
39
+ const queue = [root]
40
+ let seen = 0
41
+ while (queue.length > 0 && seen < 500) {
42
+ const current = queue.shift()
43
+ seen += 1
44
+ let entries
45
+ try {
46
+ entries = readdirSync(current, { withFileTypes: true })
47
+ } catch {
48
+ continue
49
+ }
50
+ for (const entry of entries) {
51
+ const path = join(current, entry.name)
52
+ if (entry.isDirectory()) {
53
+ if (entry.name !== 'node_modules' && entry.name !== '.git') queue.push(path)
54
+ continue
55
+ }
56
+ if (entry.name !== 'agent.cordis.yml') continue
57
+ let text
58
+ try {
59
+ text = readFileSync(path, 'utf8')
60
+ } catch {
61
+ continue
62
+ }
63
+ if (text.includes('prefix:') && text.includes('[Role Identification]')) return path
64
+ }
65
+ }
66
+ return undefined
67
+ }
68
+
69
+ /** Natural sentences of a rule text, normalized for comparison. */
70
+ export function sentences(text) {
71
+ return String(text)
72
+ .replace(/\r/g, '')
73
+ .split(/\n\s*-\s+|\n\n+|(?<=[.!?])\s+/)
74
+ .map((part) => part.replace(/\s+/g, ' ').replace(/^[\s>*#-]+/, '').trim())
75
+ .filter((part) => part.length > 12)
76
+ }
77
+
78
+ /** A rough overlap score: how much of one sentence survives inside the other. */
79
+ function sameSentence(left, right) {
80
+ const key = (value) => value.toLowerCase().replace(/[^a-z0-9 ]/g, '').replace(/\s+/g, ' ').trim()
81
+ const a = key(left)
82
+ const b = key(right)
83
+ if (a === b) return true
84
+ const shorter = a.length <= b.length ? a : b
85
+ const longer = a.length <= b.length ? b : a
86
+ if (shorter.length < 40) return false
87
+ return longer.includes(shorter)
88
+ }
89
+
90
+ /** Report the origin sentences this block does not carry, and the reverse. */
91
+ export function compare(originText, localText = DISPATCHER_RULES) {
92
+ const origin = sentences(originText)
93
+ const local = sentences(localText)
94
+ const missing = origin.filter((candidate) => local.some((entry) => sameSentence(candidate, entry)) !== true)
95
+ const extra = local.filter((candidate) => origin.some((entry) => sameSentence(candidate, entry)) !== true)
96
+ return { missing, extra }
97
+ }
98
+
99
+ const isMain = process.argv[1] !== undefined && process.argv[1].endsWith('check-dispatcher-rules.mjs')
100
+ if (isMain) {
101
+ const strict = process.argv.includes('--strict')
102
+ const verbose = process.argv.includes('--verbose')
103
+ const root = originRoot()
104
+ if (root === undefined) {
105
+ console.log(ORIGIN + ' is not installed; nothing to compare against. '
106
+ + DISPATCHER_RULES_PROVENANCE.package + ' was last read at version ' + DISPATCHER_RULES_PROVENANCE.inheritedVersion
107
+ + ', re-extracted ' + DISPATCHER_RULES_PROVENANCE.reExtractedAt + '.')
108
+ process.exit(strict ? 4 : 0)
109
+ }
110
+ const file = originPresetFile(root)
111
+ if (file === undefined) {
112
+ console.log('installed ' + ORIGIN + ', but no dispatch preset with a persona prefix was found under ' + root + '; layout not recognized.')
113
+ process.exit(0)
114
+ }
115
+ const originText = readFileSync(file, 'utf8')
116
+ const result = compare(originText)
117
+ const drifted = result.missing.length > 0 || result.extra.length > 0
118
+ console.log('origin ' + file)
119
+ console.log('local ' + DISPATCHER_RULES_PROVENANCE.reExtractedAt + ', ' + DISPATCHER_RULES_PROVENANCE.corrections.length + ' correction(s) recorded')
120
+ if (drifted === false) {
121
+ console.log('no drift: every comparable sentence matches.')
122
+ process.exit(0)
123
+ }
124
+ console.log('drift: ' + result.missing.length + ' origin sentence(s) not carried, ' + result.extra.length + ' local sentence(s) not in origin.')
125
+ const show = verbose ? 40 : 8
126
+ for (const entry of result.missing.slice(0, show)) console.log(' origin only: ' + entry.slice(0, 160))
127
+ for (const entry of result.extra.slice(0, show)) console.log(' local only: ' + entry.slice(0, 160))
128
+ console.log('A difference is not automatically a defect: the provenance record lists the corrections that are meant to differ.')
129
+ process.exit(3)
130
+ }