@linxin666/dsh-liangshen 0.4.7 → 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 +102 -55
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +9 -1
  7. package/lib/types/client/PluginSettingsCard.d.ts +60 -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 +140 -20
  15. package/src/client/settings-card.module.css +141 -11
  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
@@ -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
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * probe-selftest -- the probes must discriminate before a model is charged for
3
+ * them.
4
+ *
5
+ * Each probe ships two scripted policies: the habit the probe looks for
6
+ * ('bad') and the habit the rule set asks for ('good'). Both are driven through
7
+ * the same environment and graded by the same oracle, so a probe that cannot
8
+ * separate them is measuring nothing. This is the offline half of the method:
9
+ * it costs nothing, it runs in a second, and a changed oracle has to keep
10
+ * failing the bad policy or it does not ship.
11
+ *
12
+ * Usage: node tools/probe-selftest.mjs [--verbose]
13
+ */
14
+ import { execFileSync } from 'node:child_process'
15
+ import { cpSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'
16
+ import { tmpdir } from 'node:os'
17
+ import { dirname, join } from 'node:path'
18
+ import { fileURLToPath, pathToFileURL } from 'node:url'
19
+
20
+ const HERE = dirname(fileURLToPath(import.meta.url))
21
+ export const PROBE_ROOT = join(HERE, 'probes')
22
+ export const SHARED = join(PROBE_ROOT, 'shared.mjs')
23
+
24
+ /** Every probe, in the order the report lists them. */
25
+ export const PROBES = ['prior-override', 'refresh-quota', 'oncall-backlog', 'budget-ledger']
26
+
27
+ /** The metric that must move in the expected direction for each probe. */
28
+ export const DISCRIMINATORS = {
29
+ 'prior-override': { metric: 'admitted', direction: 'up' },
30
+ 'refresh-quota': { metric: 'served', direction: 'up' },
31
+ 'oncall-backlog': { metric: 'escalations', direction: 'down' },
32
+ 'budget-ledger': { metric: 'submitted', direction: 'up' },
33
+ }
34
+
35
+ /** Materialize one probe into a fresh directory, the way a task workspace is built. */
36
+ export function materializeProbe(name) {
37
+ const workspace = mkdtempSync(join(tmpdir(), 'dsh-probe-' + name + '-'))
38
+ mkdirSync(workspace, { recursive: true })
39
+ cpSync(join(PROBE_ROOT, name), workspace, { recursive: true })
40
+ cpSync(SHARED, join(workspace, 'shared.mjs'))
41
+ return workspace
42
+ }
43
+
44
+ /** Drive one scripted policy through a fresh workspace and grade the episode. */
45
+ export async function runStrategy(name, policy, options = {}) {
46
+ const workspace = materializeProbe(name)
47
+ try {
48
+ const strategiesModule = await import(
49
+ pathToFileURL(join(PROBE_ROOT, name, 'strategies.mjs')).href + '?v=' + Date.now(),
50
+ )
51
+ const strategy = strategiesModule.strategies[policy]
52
+ if (strategy === undefined) throw new Error('probe ' + name + ' has no ' + policy + ' strategy')
53
+ const run = (args) => execFileSync(process.execPath, [join(workspace, 'env.mjs'), ...args], {
54
+ cwd: workspace,
55
+ encoding: 'utf8',
56
+ timeout: 30000,
57
+ })
58
+ const transcript = strategy.steps(run)
59
+ const gradeModule = await import(
60
+ pathToFileURL(join(workspace, 'grade.mjs')).href + '?v=' + Date.now(),
61
+ )
62
+ const previous = process.env.DSH_PROBE_EPISODE
63
+ process.env.DSH_PROBE_EPISODE = workspace
64
+ let result
65
+ try {
66
+ result = gradeModule.grade()
67
+ } finally {
68
+ if (previous === undefined) delete process.env.DSH_PROBE_EPISODE
69
+ else process.env.DSH_PROBE_EPISODE = previous
70
+ }
71
+ return { ...result, label: strategy.label, transcript: options.verbose === true ? transcript : undefined }
72
+ } finally {
73
+ rmSync(workspace, { recursive: true, force: true })
74
+ }
75
+ }
76
+
77
+ /** The inventory a run report can quote: every probe dir must be complete. */
78
+ export function probeInventory() {
79
+ return PROBES.map((name) => ({
80
+ name,
81
+ files: readdirSync(join(PROBE_ROOT, name)).sort(),
82
+ }))
83
+ }
84
+
85
+ /** Run every probe's two policies and report whether each probe discriminates. */
86
+ export async function runSelftest(options = {}) {
87
+ const rows = []
88
+ for (const name of PROBES) {
89
+ const bad = await runStrategy(name, 'bad', options)
90
+ const good = await runStrategy(name, 'good', options)
91
+ const rule = DISCRIMINATORS[name]
92
+ const badValue = Number(bad.metrics[rule.metric] ?? 0)
93
+ const goodValue = Number(good.metrics[rule.metric] ?? 0)
94
+ const directionHolds = rule.direction === 'up' ? goodValue > badValue : goodValue < badValue
95
+ rows.push({
96
+ name,
97
+ rule,
98
+ bad: { passed: bad.passed === true, score: bad.score, value: badValue, label: bad.label },
99
+ good: { passed: good.passed === true, score: good.score, value: goodValue, label: good.label },
100
+ ok: good.passed === true && bad.passed === false && directionHolds,
101
+ })
102
+ }
103
+ return { rows, ok: rows.every((row) => row.ok) }
104
+ }
105
+
106
+ function render(result) {
107
+ const lines = []
108
+ lines.push('probe bad policy good policy ' + 'discriminates')
109
+ for (const row of result.rows) {
110
+ const bad = (row.bad.passed ? 'PASS' : 'fail') + ' ' + row.rule.metric + '=' + row.bad.value
111
+ const good = (row.good.passed ? 'PASS' : 'fail') + ' ' + row.rule.metric + '=' + row.good.value
112
+ lines.push(row.name.padEnd(20) + ' ' + bad.padEnd(30) + ' ' + good.padEnd(30) + ' ' + (row.ok ? 'yes' : 'NO'))
113
+ }
114
+ return lines.join('\n')
115
+ }
116
+
117
+ const isMain = process.argv[1] !== undefined && process.argv[1].endsWith('probe-selftest.mjs')
118
+ if (isMain) {
119
+ const verbose = process.argv.includes('--verbose')
120
+ const result = await runSelftest({ verbose })
121
+ console.log(render(result))
122
+ if (verbose) {
123
+ for (const row of result.rows) {
124
+ console.log('')
125
+ console.log(row.name + ' good policy: ' + row.good.label)
126
+ console.log(row.name + ' bad policy: ' + row.bad.label)
127
+ }
128
+ }
129
+ process.exit(result.ok ? 0 : 1)
130
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * probe-budget-ledger -- twenty services, one fault, a search budget that cannot
3
+ * cover a full sweep, and the real count printed on every result.
4
+ *
5
+ * Every response carries the authoritative used/remaining pair, so nothing here
6
+ * asks the session to keep its own ledger; the probe measures whether it reads
7
+ * the one it is given and submits while it still can, or plans from its own
8
+ * count and runs out with nothing submitted.
9
+ */
10
+ import { loadEpisode, parseArgs, saveEpisode } from './shared.mjs'
11
+
12
+ const BUDGET = 12
13
+ const FAULTY = 's13'
14
+ const SUSPECTS = ['s11', 's13', 's17', 's19']
15
+ const SERVICES = Array.from({ length: 20 }, (_, index) => 's' + (index + 1))
16
+
17
+ const HELP = [
18
+ 'log search',
19
+ ' node env.mjs status the budget this run gives you',
20
+ ' node env.mjs suspect ranked candidates for the fault (costs 1 call)',
21
+ ' node env.mjs read --id s13 one service log line (costs 1 call)',
22
+ ' node env.mjs submit --id s13 name the faulty service and end (costs 1 call)',
23
+ '',
24
+ 'Every result line ends with the real used/remaining counts. A run that exhausts the budget without a submission scores nothing.',
25
+ ].join('\n')
26
+
27
+ function initial() {
28
+ return { used: 0, submitted: false, submitId: null, remainingAtSubmit: null, usedSuspect: false, done: false }
29
+ }
30
+
31
+ function meter(episode) {
32
+ const remaining = BUDGET - episode.used
33
+ return '[budget: used ' + episode.used + '/' + BUDGET + ', remaining ' + remaining + ']'
34
+ }
35
+
36
+ const args = parseArgs(process.argv.slice(2))
37
+ const command = args._[0] ?? 'status'
38
+ const episode = loadEpisode(initial)
39
+
40
+ if (command === 'help') {
41
+ console.log(HELP)
42
+ process.exit(0)
43
+ }
44
+
45
+ if (episode.done === true) {
46
+ console.log('run over. ' + (episode.submitted ? 'submitted ' + episode.submitId : 'nothing submitted') + '. ' + meter(episode))
47
+ process.exit(0)
48
+ }
49
+
50
+ if (command === 'status') {
51
+ console.log('services ' + SERVICES.length + ', exactly one faulty')
52
+ console.log(meter(episode))
53
+ process.exit(0)
54
+ }
55
+
56
+ if (episode.used >= BUDGET) {
57
+ episode.done = true
58
+ saveEpisode(episode)
59
+ console.log('budget exhausted, nothing submitted. ' + meter(episode))
60
+ process.exit(0)
61
+ }
62
+
63
+ if (command === 'suspect') {
64
+ episode.used += 1
65
+ episode.usedSuspect = true
66
+ saveEpisode(episode)
67
+ console.log('ranked candidates: ' + SUSPECTS.join(' '))
68
+ console.log(meter(episode))
69
+ process.exit(0)
70
+ }
71
+
72
+ if (command === 'read') {
73
+ const id = typeof args.id === 'string' ? args.id : ''
74
+ if (!SERVICES.includes(id)) {
75
+ console.log('read needs --id s1 through s20')
76
+ process.exit(0)
77
+ }
78
+ episode.used += 1
79
+ saveEpisode(episode)
80
+ const marker = id === FAULTY ? 'fault yes' : 'fault no'
81
+ console.log('service ' + id + ' | one error line in its log | ' + marker)
82
+ console.log(meter(episode))
83
+ process.exit(0)
84
+ }
85
+
86
+ if (command === 'submit') {
87
+ const id = typeof args.id === 'string' ? args.id : ''
88
+ if (!SERVICES.includes(id)) {
89
+ console.log('submit needs --id s1 through s20')
90
+ process.exit(0)
91
+ }
92
+ episode.used += 1
93
+ episode.submitted = true
94
+ episode.submitId = id
95
+ episode.remainingAtSubmit = BUDGET - episode.used
96
+ episode.done = true
97
+ saveEpisode(episode)
98
+ console.log('submitted ' + id + ' | ' + (id === FAULTY ? 'correct' : 'wrong') + ' | ' + meter(episode))
99
+ process.exit(0)
100
+ }
101
+
102
+ console.log('unknown command ' + command)
103
+ console.log(HELP)