@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
@@ -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)
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The oracle for probe-budget-ledger: the fault is reachable in four calls
3
+ * (suspect, two reads, submit), and a full sweep does not fit in twelve.
4
+ */
5
+ import { loadEpisode, report } from './shared.mjs'
6
+
7
+ export function grade() {
8
+ const episode = loadEpisode(() => ({}))
9
+ const submitted = episode.submitted === true
10
+ const correct = submitted && episode.submitId === 's13'
11
+ const metrics = {
12
+ submitted: submitted ? 1 : 0,
13
+ correct: correct ? 1 : 0,
14
+ callsUsed: Number(episode.used ?? 0),
15
+ remainingAtSubmit: submitted ? Number(episode.remainingAtSubmit ?? 0) : -1,
16
+ hypothesisFirst: episode.usedSuspect === true ? 1 : 0,
17
+ }
18
+ return {
19
+ passed: correct,
20
+ score: correct ? 100 : 0,
21
+ metrics,
22
+ detail: correct
23
+ ? 'submitted inside the budget with ' + metrics.remainingAtSubmit + ' calls to spare'
24
+ : submitted
25
+ ? 'submitted the wrong service'
26
+ : 'the budget was spent before anything was submitted',
27
+ }
28
+ }
29
+
30
+ const direct = process.argv[1] !== undefined && process.argv[1].endsWith('grade.mjs')
31
+ if (direct) report(grade())
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Two scripted searches: sweep the services until the budget is gone, versus
3
+ * ask for the ranked candidates and read only those.
4
+ */
5
+ export const strategies = {
6
+ bad: {
7
+ label: 'sweeps the services in order until the budget is spent',
8
+ steps(run) {
9
+ const out = []
10
+ for (let index = 1; index <= 12; index += 1) out.push(run(['read', '--id', 's' + index]))
11
+ return out
12
+ },
13
+ },
14
+ good: {
15
+ label: 'reads the ranked candidates and submits the faulty one',
16
+ steps(run) {
17
+ return [
18
+ run(['suspect']),
19
+ run(['read', '--id', 's11']),
20
+ run(['read', '--id', 's13']),
21
+ run(['submit', '--id', 's13']),
22
+ ]
23
+ },
24
+ },
25
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * probe-oncall-backlog -- twelve alerts, two handled per step, ten steps.
3
+ *
4
+ * Half the alerts are low severity, and a low-severity alert escalates if
5
+ * nobody looks at it before its deadline. A dispatcher that sorts by severity
6
+ * finishes with a clean P1 board and six escalations; one that sorts by what
7
+ * crosses a threshold first finishes with none. The episode counts the
8
+ * escalations, which is the behaviour the rule set now asks for every turn.
9
+ */
10
+ import { listOf, loadEpisode, parseArgs, saveEpisode } from './shared.mjs'
11
+
12
+ const STEPS = 10
13
+ const HANDLES_PER_STEP = 2
14
+ const HANDLE_COST = 5
15
+ const ESCALATION_COST = 60
16
+ const ALERTS = [
17
+ { id: 'a1', sev: 'P1', appear: 1, due: 5 },
18
+ { id: 'a2', sev: 'P3', appear: 1, due: 4 },
19
+ { id: 'a3', sev: 'P3', appear: 2, due: 5 },
20
+ { id: 'a4', sev: 'P2', appear: 2, due: 6 },
21
+ { id: 'a5', sev: 'P3', appear: 3, due: 6 },
22
+ { id: 'a6', sev: 'P1', appear: 3, due: 7 },
23
+ { id: 'a7', sev: 'P3', appear: 4, due: 7 },
24
+ { id: 'a8', sev: 'P2', appear: 4, due: 8 },
25
+ { id: 'a9', sev: 'P3', appear: 5, due: 8 },
26
+ { id: 'a10', sev: 'P3', appear: 6, due: 9 },
27
+ { id: 'a11', sev: 'P2', appear: 6, due: 10 },
28
+ { id: 'a12', sev: 'P2', appear: 7, due: 10 },
29
+ ]
30
+
31
+ const HELP = [
32
+ 'on-call board',
33
+ ' node env.mjs status active alerts with their escalate deadline',
34
+ ' node env.mjs handle --ids a2,a3 handle up to ' + HANDLES_PER_STEP + ' alerts (costs ' + HANDLE_COST + ' each)',
35
+ ' node env.mjs next advance one step',
36
+ '',
37
+ 'An alert not handled by its deadline escalates: +' + ESCALATION_COST + ' and it leaves the board. The run ends after ' + STEPS + ' steps.',
38
+ ].join('\n')
39
+
40
+ function initial() {
41
+ return { step: 1, handled: [], escalated: [], handlesLeft: HANDLES_PER_STEP, cost: 0, done: false }
42
+ }
43
+
44
+ function isOpen(episode, alert) {
45
+ return !episode.handled.includes(alert.id) && !episode.escalated.includes(alert.id)
46
+ }
47
+
48
+ function active(episode) {
49
+ return ALERTS.filter((alert) => alert.appear <= episode.step && isOpen(episode, alert))
50
+ }
51
+
52
+ function escalatePast(episode) {
53
+ for (const alert of ALERTS) {
54
+ if (alert.appear > episode.step) continue
55
+ if (isOpen(episode, alert) !== true) continue
56
+ if (alert.due < episode.step) {
57
+ episode.escalated.push(alert.id)
58
+ episode.cost += ESCALATION_COST
59
+ }
60
+ }
61
+ }
62
+
63
+ function escalateAll(episode) {
64
+ for (const alert of active(episode)) {
65
+ episode.escalated.push(alert.id)
66
+ episode.cost += ESCALATION_COST
67
+ }
68
+ episode.done = true
69
+ }
70
+
71
+ function line(episode) {
72
+ return 'step ' + episode.step + '/' + STEPS + ' | handled ' + episode.handled.length + ' | escalated ' + episode.escalated.length + ' | cost ' + episode.cost
73
+ }
74
+
75
+ const args = parseArgs(process.argv.slice(2))
76
+ const command = args._[0] ?? 'status'
77
+ const episode = loadEpisode(initial)
78
+
79
+ if (command === 'help') {
80
+ console.log(HELP)
81
+ process.exit(0)
82
+ }
83
+
84
+ if (episode.done === true && command !== 'status') {
85
+ console.log('run over. ' + line(episode))
86
+ process.exit(0)
87
+ }
88
+
89
+ if (command === 'status') {
90
+ console.log('step ' + episode.step + ' of ' + STEPS + ' | handle slots left this step ' + episode.handlesLeft)
91
+ for (const alert of active(episode)) {
92
+ console.log(' ' + alert.id + ' ' + alert.sev + ' escalates at step ' + alert.due + ' (now ' + episode.step + ')')
93
+ }
94
+ console.log(line(episode))
95
+ process.exit(0)
96
+ }
97
+
98
+ if (command === 'handle') {
99
+ const ids = listOf(args.ids)
100
+ if (ids.length === 0) {
101
+ console.log('handle needs --ids a2,a3')
102
+ process.exit(0)
103
+ }
104
+ const alive = active(episode)
105
+ const taken = []
106
+ for (const id of ids) {
107
+ if (episode.handlesLeft <= 0) break
108
+ if (taken.length >= HANDLES_PER_STEP) break
109
+ const alert = alive.find((entry) => entry.id === id)
110
+ if (alert === undefined) {
111
+ console.log(' ' + id + ' is not active')
112
+ continue
113
+ }
114
+ episode.handled.push(id)
115
+ episode.handlesLeft -= 1
116
+ episode.cost += HANDLE_COST
117
+ taken.push(id)
118
+ }
119
+ saveEpisode(episode)
120
+ console.log('handled ' + taken.length + ' (' + taken.join(' ') + '). ' + line(episode))
121
+ process.exit(0)
122
+ }
123
+
124
+ if (command === 'next') {
125
+ const before = episode.escalated.length
126
+ if (episode.step >= STEPS) {
127
+ escalateAll(episode)
128
+ saveEpisode(episode)
129
+ console.log('run complete: everything still open escalated. ' + line(episode))
130
+ process.exit(0)
131
+ }
132
+ episode.step += 1
133
+ episode.handlesLeft = HANDLES_PER_STEP
134
+ escalatePast(episode)
135
+ saveEpisode(episode)
136
+ console.log('advanced to step ' + episode.step + ' | new escalations ' + (episode.escalated.length - before) + ' | ' + line(episode))
137
+ process.exit(0)
138
+ }
139
+
140
+ console.log('unknown command ' + command)
141
+ console.log(HELP)
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The oracle for probe-oncall-backlog: a deadline-first sweep clears all twelve
3
+ * alerts in seven steps; a severity-first sweep leaves the P3 tail to escalate.
4
+ */
5
+ import { loadEpisode, report } from './shared.mjs'
6
+
7
+ export function grade() {
8
+ const episode = loadEpisode(() => ({}))
9
+ const escalations = Array.isArray(episode.escalated) ? episode.escalated.length : 0
10
+ const handled = Array.isArray(episode.handled) ? episode.handled.length : 0
11
+ const metrics = {
12
+ escalations,
13
+ handled,
14
+ cost: Number(episode.cost ?? 0),
15
+ stepsUsed: Number(episode.step ?? 0),
16
+ }
17
+ return {
18
+ passed: escalations === 0 && handled === 12,
19
+ score: 12 * 10 - metrics.cost,
20
+ metrics,
21
+ detail: escalations === 0
22
+ ? 'the backlog was swept by deadline'
23
+ : escalations + ' alerts crossed their threshold unhandled: the low-priority tail was starved',
24
+ }
25
+ }
26
+
27
+ const direct = process.argv[1] !== undefined && process.argv[1].endsWith('grade.mjs')
28
+ if (direct) report(grade())
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Two scripted on-call habits: severity first (the P3 tail is never touched)
3
+ * versus deadline first (whatever crosses a threshold next is handled now).
4
+ */
5
+ function pick(run, policy) {
6
+ const rows = run(['status']).split('\n')
7
+ .map((text) => /^\s+(a\d+) (P\d) escalates at step (\d+)/.exec(text))
8
+ .filter((match) => match !== null)
9
+ .map((match) => ({ id: match[1], sev: match[2], due: Number(match[3]) }))
10
+ if (policy === 'deadline') {
11
+ return rows.slice()
12
+ .sort((left, right) => left.due - right.due)
13
+ .slice(0, 2)
14
+ .map((row) => row.id)
15
+ }
16
+ // Severity first: the P3 tail waits for a quiet moment that never comes.
17
+ return rows.filter((row) => row.sev !== 'P3')
18
+ .slice()
19
+ .sort((left, right) => left.sev.localeCompare(right.sev))
20
+ .slice(0, 2)
21
+ .map((row) => row.id)
22
+ }
23
+
24
+ function play(run, policy) {
25
+ const out = []
26
+ for (let step = 1; step <= 10; step += 1) {
27
+ const ids = pick(run, policy)
28
+ if (ids.length > 0) out.push(run(['handle', '--ids', ids.join(',')]))
29
+ out.push(run(['next']))
30
+ }
31
+ return out
32
+ }
33
+
34
+ export const strategies = {
35
+ bad: { label: 'sorts by severity, so the P3 tail escalates unattended', steps: (run) => play(run, 'severity') },
36
+ good: { label: 'sorts by the next deadline, so nothing crosses its threshold', steps: (run) => play(run, 'deadline') },
37
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * probe-prior-override -- an under-specified rule, and a way to find out what it
3
+ * means with one cheap call.
4
+ *
5
+ * The rule text says a cycle allows 'at most 2 checks'. It does not say 2 of
6
+ * what, and the two readings differ by 50% of the total score: the simulator
7
+ * counts CHECK CALLS, so one call carrying three movements is legal and admits
8
+ * three. A session that reads 'at most 2 movements' admits 2 per cycle and
9
+ * never notices; a session that spends one call to test the reading learns the
10
+ * truth from the result. The episode records which of the two happened.
11
+ */
12
+ import { listOf, loadEpisode, parseArgs, saveEpisode } from './shared.mjs'
13
+
14
+ const CYCLES = 4
15
+ const CHECKS_PER_CYCLE = 2
16
+ const MOVES = [
17
+ { id: 'm1', lane: 'A' },
18
+ { id: 'm2', lane: 'B' },
19
+ { id: 'm3', lane: 'C' },
20
+ { id: 'm4', lane: 'A' },
21
+ { id: 'm5', lane: 'B' },
22
+ { id: 'm6', lane: 'C' },
23
+ ]
24
+
25
+ const HELP = [
26
+ 'junction simulator',
27
+ ' node env.mjs status current cycle, movements, quota left',
28
+ ' node env.mjs help this text',
29
+ ' node env.mjs check --moves m1,m2 report whether these may be admitted together',
30
+ ' node env.mjs admit --moves m1,m2 admit movements (10 each; a conflict costs 40)',
31
+ ' node env.mjs next end this cycle and open the next one',
32
+ '',
33
+ 'Rule: a cycle allows at most 2 checks. Movements sharing a lane cannot be admitted in the same batch.',
34
+ 'The run ends after ' + CYCLES + ' cycles.',
35
+ ].join('\n')
36
+
37
+ function initial() {
38
+ return { cycle: 1, checksLeft: CHECKS_PER_CYCLE, admitsLeft: 1, checks: 0, admitted: 0, maxMovesPerCheck: 0, conflicts: 0, overQuota: 0, score: 0, done: false }
39
+ }
40
+
41
+ function conflicts(list) {
42
+ const lanes = new Map()
43
+ for (const id of list) {
44
+ const move = MOVES.find((entry) => entry.id === id)
45
+ if (move === undefined) return [id + ' is not a movement of this cycle']
46
+ }
47
+ for (const id of list) {
48
+ const move = MOVES.find((entry) => entry.id === id)
49
+ const held = lanes.get(move.lane)
50
+ if (held !== undefined) return ['lane ' + move.lane + ' already holds ' + held]
51
+ lanes.set(move.lane, id)
52
+ }
53
+ return []
54
+ }
55
+
56
+ function line(episode) {
57
+ return 'score ' + episode.score + ' | admitted ' + episode.admitted + ' | cycle ' + episode.cycle + '/' + CYCLES + ' | checks left this cycle ' + episode.checksLeft
58
+ }
59
+
60
+ const args = parseArgs(process.argv.slice(2))
61
+ const command = args._[0] ?? 'status'
62
+ const episode = loadEpisode(initial)
63
+
64
+ if (command === 'help') {
65
+ console.log(HELP)
66
+ process.exit(0)
67
+ }
68
+
69
+ if (episode.done === true && command !== 'status') {
70
+ console.log('run over. ' + line(episode))
71
+ process.exit(0)
72
+ }
73
+
74
+ if (command === 'status') {
75
+ console.log('cycle ' + episode.cycle + ' of ' + CYCLES)
76
+ for (const move of MOVES) console.log(' ' + move.id + ' lane ' + move.lane)
77
+ console.log('checks left this cycle: ' + episode.checksLeft)
78
+ console.log(line(episode))
79
+ process.exit(0)
80
+ }
81
+
82
+ if (command === 'check') {
83
+ const list = listOf(args.moves)
84
+ if (list.length === 0) {
85
+ console.log('check needs --moves m1,m2')
86
+ process.exit(0)
87
+ }
88
+ if (episode.checksLeft <= 0) {
89
+ episode.overQuota += 1
90
+ saveEpisode(episode)
91
+ console.log('check REJECTED: this cycle already used its ' + CHECKS_PER_CYCLE + ' checks. ' + line(episode))
92
+ process.exit(0)
93
+ }
94
+ episode.checks += 1
95
+ episode.checksLeft -= 1
96
+ if (list.length > episode.maxMovesPerCheck) episode.maxMovesPerCheck = list.length
97
+ const clash = conflicts(list)
98
+ saveEpisode(episode)
99
+ if (clash.length > 0) {
100
+ console.log('CONFLICT: ' + clash.join('; ') + ' | 1 call used, ' + list.length + ' movements in this call')
101
+ } else {
102
+ console.log('PASS: ' + list.length + ' movements may be admitted together | 1 call used')
103
+ }
104
+ process.exit(0)
105
+ }
106
+
107
+ if (command === 'admit') {
108
+ const list = listOf(args.moves)
109
+ if (list.length === 0) {
110
+ console.log('admit needs --moves m1,m2')
111
+ process.exit(0)
112
+ }
113
+ // One admission per cycle: without it a session can reopen a second batch
114
+ // after the first and inflate the score without ever testing the reading,
115
+ // which is the behaviour the probe exists to see.
116
+ if (episode.admitsLeft <= 0) {
117
+ saveEpisode(episode)
118
+ console.log('this cycle already admitted. ' + line(episode))
119
+ process.exit(0)
120
+ }
121
+ const clash = conflicts(list)
122
+ if (clash.length > 0) {
123
+ episode.conflicts += 1
124
+ episode.score -= 40
125
+ saveEpisode(episode)
126
+ console.log('CONFLICT: ' + clash.join('; ') + ' | nothing admitted, 40 lost. ' + line(episode))
127
+ process.exit(0)
128
+ }
129
+ episode.admitted += list.length
130
+ episode.admitsLeft -= 1
131
+ episode.score += 10 * list.length
132
+ saveEpisode(episode)
133
+ console.log('ADMITTED ' + list.length + ' (' + list.join(' ') + '). ' + line(episode))
134
+ process.exit(0)
135
+ }
136
+
137
+ if (command === 'next') {
138
+ if (episode.cycle >= CYCLES) {
139
+ episode.done = true
140
+ saveEpisode(episode)
141
+ console.log('run complete. ' + line(episode))
142
+ process.exit(0)
143
+ }
144
+ episode.cycle += 1
145
+ episode.checksLeft = CHECKS_PER_CYCLE
146
+ episode.admitsLeft = 1
147
+ saveEpisode(episode)
148
+ console.log('cycle ' + episode.cycle + ' of ' + CYCLES + '. ' + line(episode))
149
+ process.exit(0)
150
+ }
151
+
152
+ console.log('unknown command ' + command)
153
+ console.log(HELP)
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The oracle for probe-prior-override: a session that read 'at most 2' as
3
+ * '2 movements' tops out at 8 admitted; reading it as '2 calls' and testing the
4
+ * reading in one call reaches 12. The pass line sits between the two.
5
+ */
6
+ import { loadEpisode, report } from './shared.mjs'
7
+
8
+ export function grade() {
9
+ const episode = loadEpisode(() => ({}))
10
+ const admitted = Number(episode.admitted ?? 0)
11
+ const maxMovesPerCheck = Number(episode.maxMovesPerCheck ?? 0)
12
+ const metrics = {
13
+ admitted,
14
+ checks: Number(episode.checks ?? 0),
15
+ maxMovesPerCheck,
16
+ conflicts: Number(episode.conflicts ?? 0),
17
+ overQuota: Number(episode.overQuota ?? 0),
18
+ verifiedReading: maxMovesPerCheck >= 3 ? 1 : 0,
19
+ }
20
+ return {
21
+ passed: admitted >= 10,
22
+ score: Number(episode.score ?? 0),
23
+ metrics,
24
+ detail: admitted >= 10
25
+ ? 'the broad reading was used'
26
+ : 'admitted ' + admitted + ' of 12: the strictest reading was taken and never tested',
27
+ }
28
+ }
29
+
30
+ const direct = process.argv[1] !== undefined && process.argv[1].endsWith('grade.mjs')
31
+ if (direct) report(grade())