dsh-memory-bond 0.3.0-beta.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -7
- package/README.md +125 -91
- package/README.zh-CN.md +122 -92
- package/SECURITY.md +29 -0
- package/dist/audit.js +155 -80
- package/dist/automatic.js +10 -2
- package/dist/client.js +2035 -0
- package/dist/command-scope.js +4 -4
- package/dist/commands.js +15 -9
- package/dist/consolidation-store.js +87 -20
- package/dist/consolidation.js +2 -6
- package/dist/domain.js +8 -4
- package/dist/encoder.js +46 -5
- package/dist/file-import-store.js +120 -0
- package/dist/file-import.js +265 -0
- package/dist/foreground-attempts.js +91 -0
- package/dist/guidance.js +133 -92
- package/dist/host.js +13 -0
- package/dist/index-policy.js +91 -48
- package/dist/index.js +102 -40
- package/dist/knowledge-hooks.js +70 -27
- package/dist/knowledge.js +2 -3
- package/dist/maintenance-store.js +38 -4
- package/dist/maintenance.js +29 -5
- package/dist/personal.js +37 -0
- package/dist/policy.js +45 -47
- package/dist/prompt-copy.js +93 -0
- package/dist/proposal-receipts.js +70 -0
- package/dist/proposal-review.js +656 -0
- package/dist/propose-contract.js +32 -36
- package/dist/question-answers.js +86 -29
- package/dist/retrieval.js +25 -8
- package/dist/scope-narrowing.js +49 -0
- package/dist/search-index.js +93 -13
- package/dist/semantic.js +69 -207
- package/dist/service.js +633 -204
- package/dist/sharing.js +7 -13
- package/dist/sources.js +28 -3
- package/dist/store.js +432 -96
- package/dist/tool-experience.js +87 -0
- package/dist/turn-review-store.js +83 -16
- package/dist/turn-review.js +155 -59
- package/dist/ui.js +128 -26
- package/dist/vector-index.js +69 -33
- package/docs/architecture.zh-CN.md +52 -0
- package/docs/benchmark.zh-CN.md +60 -0
- package/docs/benchmarks/repository-tasks.json +5355 -0
- package/docs/images/bond-memory-principle-en.svg +644 -0
- package/docs/images/bond-memory-principle-zh.svg +644 -0
- package/docs/images/bond-memory-principle.drawio +644 -0
- package/docs/images/memory-settings-en.png +0 -0
- package/docs/images/memory-settings-zh.png +0 -0
- package/docs/images/memory-turn-recalled-en.png +0 -0
- package/docs/images/memory-turn-recalled-zh.png +0 -0
- package/docs/images/memory-turn-saved-en.png +0 -0
- package/docs/images/memory-turn-saved-zh.png +0 -0
- package/docs/media/memory-bond-name-en.gif +0 -0
- package/docs/media/memory-bond-name-en.mp4 +0 -0
- package/docs/media/memory-bond-name-zh.gif +0 -0
- package/docs/media/memory-bond-name-zh.mp4 +0 -0
- package/locale/detail.en.md +5 -1
- package/locale/detail.zh.md +5 -1
- package/locale/en.json +338 -0
- package/locale/zh.json +338 -0
- package/native/embeddings/NOTICE.md +2 -2
- package/package.json +39 -19
- package/scripts/benchmark-bond.mjs +72 -0
- package/scripts/benchmark-conditions.mjs +144 -0
- package/scripts/benchmark-example.mjs +37 -0
- package/scripts/benchmark-scale.mjs +119 -0
- package/scripts/benchmark-scenarios.mjs +57 -0
- package/scripts/benchmark-tasks.mjs +244 -0
- package/src/audit.ts +144 -85
- package/src/automatic.ts +12 -2
- package/src/command-scope.ts +4 -4
- package/src/commands.ts +12 -8
- package/src/consolidation-store.ts +80 -18
- package/src/consolidation.ts +2 -6
- package/src/domain.ts +9 -4
- package/src/encoder.ts +46 -6
- package/src/file-import-store.ts +139 -0
- package/src/file-import.ts +256 -0
- package/src/foreground-attempts.ts +97 -0
- package/src/guidance.ts +138 -102
- package/src/host.ts +22 -2
- package/src/index-policy.ts +93 -46
- package/src/index.ts +87 -43
- package/src/knowledge-hooks.ts +71 -29
- package/src/knowledge.ts +2 -3
- package/src/maintenance-store.ts +37 -4
- package/src/maintenance.ts +25 -5
- package/src/personal.ts +36 -0
- package/src/policy.ts +55 -52
- package/src/prompt-copy.ts +99 -0
- package/src/proposal-receipts.ts +59 -0
- package/src/proposal-review.ts +614 -0
- package/src/propose-contract.ts +31 -35
- package/src/question-answers.ts +99 -29
- package/src/retrieval.ts +26 -9
- package/src/scope-narrowing.ts +58 -0
- package/src/search-index.ts +94 -14
- package/src/semantic.ts +67 -188
- package/src/service.ts +595 -210
- package/src/sharing.ts +7 -14
- package/src/sources.ts +26 -4
- package/src/store.ts +434 -97
- package/src/tool-experience.ts +93 -0
- package/src/turn-review-store.ts +86 -15
- package/src/turn-review.ts +142 -60
- package/src/ui.ts +122 -27
- package/src/vector-index.ts +57 -29
- package/client/index.js +0 -1186
- package/design/dsh-memory-plugin-design.md +0 -46
- package/design/dsh-memory-plugin-evaluation.md +0 -135
- package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
- package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
- package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
- package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
- package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
- package/design/memory-lifecycle-consolidation.svg +0 -2
- package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
- package/design/memory-lifecycle.excalidraw +0 -2105
- package/design/memory-lifecycle.mobile.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.svg +0 -95
- package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
- package/design/memory-lifecycle.svg +0 -95
- package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
- package/design/memory-lifecycle.zh-CN.svg +0 -97
- package/native/embeddings/LICENSE +0 -21
- package/native/embeddings/en/model.onnx +0 -4
- package/native/embeddings/en/vocab.txt +0 -30522
- package/native/embeddings/runtime/LICENSE +0 -21
- package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
- package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
- package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
- package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
- package/native/embeddings/worker.mjs +0 -97
- package/native/embeddings/zh/model.onnx +0 -0
- package/native/embeddings/zh/vocab.txt +0 -21128
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Paired offline check of a first-result policy against condition-only verification.
|
|
2
|
+
// Both arms receive the same public hybrid tool output. Only the scorer sees the expected action.
|
|
3
|
+
import assert from 'node:assert/strict'
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import bond from './benchmark-bond.mjs'
|
|
7
|
+
import { scenarios } from './benchmark-scenarios.mjs'
|
|
8
|
+
import { normalizeLabel } from '../dist/personal.js'
|
|
9
|
+
import { SearchIndex } from '../dist/search-index.js'
|
|
10
|
+
import { encoderId, language, SentenceEncoder } from '../dist/encoder.js'
|
|
11
|
+
|
|
12
|
+
const maxRelativeGap = 0.10
|
|
13
|
+
const width = 3
|
|
14
|
+
const minimum = 0.45
|
|
15
|
+
const requiredLead = 0.05
|
|
16
|
+
|
|
17
|
+
// Separate repository and new tasks. Some task pairs share a subject but ask for different operations.
|
|
18
|
+
const newTasks = [
|
|
19
|
+
['image-layers', 'List the layers that add the most bytes to a container image',
|
|
20
|
+
'List the largest image layers', 'Which Docker build step made the image big?', 'Show the size contribution of each layer', 'Find the heavyweight layers in our container', 'Break down the image by space used'],
|
|
21
|
+
['image-platforms', 'List the operating systems and CPU architectures available in a container image',
|
|
22
|
+
'List platforms supported by our container image', 'Can we pull this image on arm64?', 'Find supported OS and architecture combinations', 'Show which architectures are in the image manifest', 'Which machines can run this container build?'],
|
|
23
|
+
['api-removed', 'Detect previously available API routes that were removed',
|
|
24
|
+
'Check for removed API routes', 'Find endpoints that vanished from the public service', 'Which old URLs stopped being available?', 'Compare the route list for deleted entries', 'Check that old clients can still reach their endpoints'],
|
|
25
|
+
['api-duplicates', 'Detect duplicate registrations of the same API route',
|
|
26
|
+
'Find duplicate API routes', 'Check whether two handlers claim the same URL', 'Look for repeated path and method pairs', 'Report collisions in route registration', 'Is an endpoint registered more than once?'],
|
|
27
|
+
['queue-retry', '按任务类型统计队列中的重试次数',
|
|
28
|
+
'统计队列任务的重试次数', '哪种任务反复被放回队列?', '按类型比较消息的重跑次数', '汇总失败任务再次投递的频率', '哪些排队作业重试最多?'],
|
|
29
|
+
['queue-delay', '按任务类型统计队列等待时间',
|
|
30
|
+
'统计每种队列任务的等待时间', '哪种任务入队后迟迟没有开始?', '按类型比较排队时长', '找出等待执行最久的作业类别', '消息从入队到开工平均要多久?'],
|
|
31
|
+
['media-duration', '核对音频与视频轨道的播放时长是否一致',
|
|
32
|
+
'核对音视频轨道时长', '画面结束时声音是否也已经结束?', '检查两条媒体流的长度差', '比对声轨和画面轨的总秒数', '检查片尾有没有多余的音轨'],
|
|
33
|
+
['media-language', '核对音频轨道标记的语言是否正确',
|
|
34
|
+
'核对音轨标注的语言', '检查声轨的语种标签', '看看配音语言元数据有没有填错', '音频流上写的是哪一种语言?', '检查每条音轨的语言代码'],
|
|
35
|
+
]
|
|
36
|
+
const unsupported = [
|
|
37
|
+
['unknown-notify', 'Send a message to the on-call engineer', 'Page the engineer on duty',
|
|
38
|
+
'Notify the release manager about this build', 'Email the service owner', 'Post the report in the team chat'],
|
|
39
|
+
['unknown-battery', '检查笔记本的电池健康', '电池还能充进去多少电?', '读取剩余电量', '查看设备的充放电循环次数', '电脑的电池是否需要更换?'],
|
|
40
|
+
]
|
|
41
|
+
const heldOut = [
|
|
42
|
+
...newTasks.map(([id, when, ...queries]) => ({ id, when, queries, repo: 'holdout' })),
|
|
43
|
+
...unsupported.map(([id, ...queries]) => ({ id, queries, repo: 'holdout', empty: true })),
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
const encoder = new SentenceEncoder()
|
|
47
|
+
const embeddings = new Map()
|
|
48
|
+
let database
|
|
49
|
+
let keywordIndex
|
|
50
|
+
|
|
51
|
+
async function embedding(text, lang) {
|
|
52
|
+
if (!embeddings.has(text)) {
|
|
53
|
+
const [vector] = await encoder.encode(lang, [text])
|
|
54
|
+
embeddings.set(text, vector)
|
|
55
|
+
}
|
|
56
|
+
return embeddings.get(text)
|
|
57
|
+
}
|
|
58
|
+
function queryVector(query) {
|
|
59
|
+
const lang = language(query)
|
|
60
|
+
const prefix = lang === 'zh' ? '为这个句子生成表示以用于检索相关文章:' : 'Represent this sentence for searching relevant passages: '
|
|
61
|
+
return embedding(prefix + normalizeLabel(query), lang)
|
|
62
|
+
}
|
|
63
|
+
const cosine = (a, b) => a.reduce((sum, n, i) => sum + n * b[i], 0)
|
|
64
|
+
|
|
65
|
+
// The model-facing search tool exposes rank but not score. Reconstruct its scores only within
|
|
66
|
+
// this synthetic profile, from the actual FTS weights and the stored public candidate vectors.
|
|
67
|
+
async function hybridGap(query, rules) {
|
|
68
|
+
if (rules.length < 2) return null
|
|
69
|
+
const { domain } = database.prepare('SELECT domain FROM heads WHERE id = ? AND rev = ?').get(rules[0].id, rules[0].rev)
|
|
70
|
+
const lexical = new Map(keywordIndex.matches([domain], query, '').map(hit => [hit.id, hit.score]))
|
|
71
|
+
const queryEmbedding = await queryVector(query)
|
|
72
|
+
const model = encoderId(language(query)) + '/passage-%'
|
|
73
|
+
const passages = database.prepare('SELECT dimensions, vector FROM memory_vectors WHERE domain=? AND id=? AND rev=? AND model LIKE ?')
|
|
74
|
+
const scores = rules.map(rule => {
|
|
75
|
+
let best = 0
|
|
76
|
+
for (const { vector, dimensions } of passages.all(domain, rule.id, rule.rev, model)) {
|
|
77
|
+
assert.equal(dimensions, queryEmbedding.length)
|
|
78
|
+
const values = new Float32Array(vector.buffer.slice(vector.byteOffset, vector.byteOffset + vector.byteLength))
|
|
79
|
+
best = Math.max(best, cosine(queryEmbedding, values))
|
|
80
|
+
}
|
|
81
|
+
return (lexical.get(rule.id) ?? 0) + 0.9 * (best >= 0.45 ? best : 0)
|
|
82
|
+
})
|
|
83
|
+
assert.ok(scores.every((score, i) => score > 0 && (!i || scores[i - 1] >= score - 1e-8)),
|
|
84
|
+
'Diagnostic fusion scores diverged from the public retrieval order')
|
|
85
|
+
return (scores[0] - scores[1]) / scores[0]
|
|
86
|
+
}
|
|
87
|
+
async function verify(query, rules) {
|
|
88
|
+
const lang = language(query)
|
|
89
|
+
const shortlist = rules.slice(0, width)
|
|
90
|
+
const comparable = shortlist.filter(r => r.when && language(r.when) === lang)
|
|
91
|
+
const byRule = new Map()
|
|
92
|
+
if (comparable.length) {
|
|
93
|
+
const probe = await queryVector(query)
|
|
94
|
+
for (const rule of comparable) byRule.set(rule, cosine(probe, await embedding(rule.when, lang)))
|
|
95
|
+
}
|
|
96
|
+
const ordered = [...byRule].sort((a, b) => b[1] - a[1])
|
|
97
|
+
const [first, next] = ordered
|
|
98
|
+
let reason = 'selected'
|
|
99
|
+
if (!first) reason = 'no_comparable_condition'
|
|
100
|
+
else if (first[1] < minimum) reason = 'weak_condition'
|
|
101
|
+
else if (next && first[1] - next[1] < requiredLead) reason = 'close_conditions'
|
|
102
|
+
return {
|
|
103
|
+
action: reason === 'selected' ? first[0].action : null,
|
|
104
|
+
decision: {
|
|
105
|
+
reason,
|
|
106
|
+
// Preserve retrieval order and full precision for independent analysis. These are condition
|
|
107
|
+
// cosines, not fused search scores. No expected target or scenario ID enters the decision.
|
|
108
|
+
rankedActions: rules.map(r => r.action),
|
|
109
|
+
conditionScores: shortlist.map(r => byRule.get(r) ?? null),
|
|
110
|
+
},
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export default {
|
|
115
|
+
...bond,
|
|
116
|
+
name: 'dsh-memory-bond-condition-check',
|
|
117
|
+
modes: ['hybrid'],
|
|
118
|
+
arms: ['first', 'closeOnly', 'checked'].map(name => ({ name, mode: 'hybrid' })),
|
|
119
|
+
scenarios: [...scenarios, ...heldOut],
|
|
120
|
+
policy: 'Native DSH Bash under three hybrid policies: first result, check when the first two fusion scores differ by at most 10% of the first, or check every search. Check the first three conditions with local BGE, minimum cosine 0.45 and minimum lead 0.05.',
|
|
121
|
+
async ready(context) {
|
|
122
|
+
const indexing = await bond.ready(context)
|
|
123
|
+
database = new DatabaseSync(join(context.profile, 'memory-bond', 'memory.sqlite'), { readOnly: true })
|
|
124
|
+
keywordIndex = new SearchIndex(database)
|
|
125
|
+
return indexing
|
|
126
|
+
},
|
|
127
|
+
close() {
|
|
128
|
+
database?.close()
|
|
129
|
+
encoder.close()
|
|
130
|
+
},
|
|
131
|
+
async result(text, { query, arm }) {
|
|
132
|
+
const data = JSON.parse(text)
|
|
133
|
+
assert.ok(Array.isArray(data.rules), 'Unexpected hybrid search response')
|
|
134
|
+
if (arm === 'first') return { action: data.rules[0]?.action, coverage: data.coverage }
|
|
135
|
+
if (arm === 'closeOnly') {
|
|
136
|
+
const gap = await hybridGap(query, data.rules)
|
|
137
|
+
const check = gap !== null && gap <= maxRelativeGap
|
|
138
|
+
const found = check ? await verify(query, data.rules) : { action: data.rules[0]?.action }
|
|
139
|
+
return { action: found.action, coverage: data.coverage,
|
|
140
|
+
decision: { relativeHybridGap: gap, checked: check, ...(check && { reason: found.decision.reason }) } }
|
|
141
|
+
}
|
|
142
|
+
return { ...await verify(query, data.rules), coverage: data.coverage }
|
|
143
|
+
},
|
|
144
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Minimal standalone DSH plugin and adapter for exercising the external contract.
|
|
2
|
+
const recordsByCwd = new Map()
|
|
3
|
+
const words = text => new Set(text.toLowerCase().match(/[\p{Script=Han}]|[a-z0-9]+/gu) ?? [])
|
|
4
|
+
|
|
5
|
+
export default {
|
|
6
|
+
name: 'example-keyword-plugin',
|
|
7
|
+
modes: ['keyword'],
|
|
8
|
+
async mount({ ctx }) {
|
|
9
|
+
ctx.tools.register({
|
|
10
|
+
name: 'example_recall',
|
|
11
|
+
description: 'Look up a convention in this project.',
|
|
12
|
+
parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },
|
|
13
|
+
output: {
|
|
14
|
+
schema: { type: 'string' },
|
|
15
|
+
render: (_input, text) => [{ type: 'text', text }],
|
|
16
|
+
},
|
|
17
|
+
execute({ query }, { agent }) {
|
|
18
|
+
const records = recordsByCwd.get(ctx.workingDirectory.get(agent.session)) ?? []
|
|
19
|
+
const queryWords = [...words(query)]
|
|
20
|
+
let action = '', best = 0
|
|
21
|
+
for (const record of records) {
|
|
22
|
+
const score = queryWords.filter(w => record.words.has(w)).length
|
|
23
|
+
if (score > best) {
|
|
24
|
+
best = score
|
|
25
|
+
action = record.action
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return action
|
|
29
|
+
},
|
|
30
|
+
})
|
|
31
|
+
},
|
|
32
|
+
async seed({ cwd }, records) {
|
|
33
|
+
recordsByCwd.set(cwd, records.filter(r => !r.withdrawn).map(r => ({ words: words(r.when), action: r.action })))
|
|
34
|
+
},
|
|
35
|
+
search(query) { return { name: 'example_recall', args: { query } } },
|
|
36
|
+
result(text) { return { action: text || null } },
|
|
37
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Run with Node >=22.18. All fixtures, SQLite transactions and queries are local.
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
|
|
4
|
+
import { cpus, tmpdir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { ProjectMemory } from '../src/service.ts'
|
|
7
|
+
import { registerKnowledge } from '../src/knowledge-hooks.ts'
|
|
8
|
+
import { semanticSlot } from '../src/personal.ts'
|
|
9
|
+
|
|
10
|
+
const repetitions = 7
|
|
11
|
+
|
|
12
|
+
async function measure(operation) {
|
|
13
|
+
await operation()
|
|
14
|
+
const samples = []
|
|
15
|
+
for (let i = 0; i < repetitions; i++) {
|
|
16
|
+
const start = performance.now()
|
|
17
|
+
await operation()
|
|
18
|
+
samples.push(performance.now() - start)
|
|
19
|
+
}
|
|
20
|
+
samples.sort((a, b) => a - b)
|
|
21
|
+
return Number(samples[Math.floor(samples.length / 2)].toFixed(2))
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function insert(store, domain, n, usage) {
|
|
25
|
+
const token = 'item' + String(n).padStart(6, '0')
|
|
26
|
+
const action = 'Apply task convention ' + token
|
|
27
|
+
const topic = 'topic' + token
|
|
28
|
+
const source = { sessionId: 'seed', storeId: 'bench', turnId: String(n), seq: n, origin: 'manual' }
|
|
29
|
+
const item = {
|
|
30
|
+
action, user_quote: action, kind: usage === 'proactive' ? 'rule' : 'fact', usage,
|
|
31
|
+
semanticTopic: topic, slot: semanticSlot('project', topic),
|
|
32
|
+
when: usage === 'proactive' ? 'during release' : '', exceptions: '', paths: [], conflicts_with_repo_guidance: false,
|
|
33
|
+
}
|
|
34
|
+
return store.commitManual(domain, source.sessionId, source, item).entries[0]
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function run(profile, scenario) {
|
|
38
|
+
const repo = join(profile, 'repo')
|
|
39
|
+
mkdirSync(repo, { recursive: true })
|
|
40
|
+
const events = [{ seq: 0, type: 'turn/start', data: { turn: 1 } }]
|
|
41
|
+
const session = { id: 'bench', header: { cwd: repo, createdAt: 1 }, inheritedEventCount: 0, snapshotEvents: () => events }
|
|
42
|
+
const agent = { id: session.id, session }
|
|
43
|
+
const hooks = new Map()
|
|
44
|
+
const host = {
|
|
45
|
+
agents: { get: () => agent }, workingDirectory: { get: () => repo }, get: () => undefined,
|
|
46
|
+
emit() {}, logger: { warn(message) { throw Error(message) } },
|
|
47
|
+
tools: { register() {}, guard: handler => hooks.set('guard', handler) },
|
|
48
|
+
on: (name, handler) => hooks.set(name, handler),
|
|
49
|
+
}
|
|
50
|
+
const memory = new ProjectMemory(host, profile, { nonGitRoots: [repo] }, () => 1)
|
|
51
|
+
try {
|
|
52
|
+
memory.store.setMemoryEnabled(true)
|
|
53
|
+
const domain = memory.domain(agent)
|
|
54
|
+
assert.ok(domain && domain.id !== memory.personal.id)
|
|
55
|
+
// An open chat observes writes in these two scopes.
|
|
56
|
+
memory.store.uiChangeStamp([domain.id, memory.personal.id])
|
|
57
|
+
registerKnowledge(host, memory)
|
|
58
|
+
const call = { agent, name: 'bash', arguments: { command: 'git status' }, callId: 'git-status' }
|
|
59
|
+
const event = { seq: 1, type: 'tool/call', data: { turn: 1, name: call.name,
|
|
60
|
+
callId: call.callId, arguments: JSON.stringify(call.arguments) } }
|
|
61
|
+
events.push(event)
|
|
62
|
+
const message = { role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'Prepare a changelog for the current release' }] }
|
|
63
|
+
memory.captureTask(agent, message, 1)
|
|
64
|
+
const usage = scenario === 'proactive' ? 'proactive' : 'on_demand'
|
|
65
|
+
let seeded = 0, local = 0, first, taskNumber = 0
|
|
66
|
+
for (const total of scenario === 'distributed' ? [5000] : [100, 1000, 5000]) {
|
|
67
|
+
for (; seeded < total; seeded++) {
|
|
68
|
+
const project = scenario === 'distributed' ? Math.floor(seeded / 100) : 0
|
|
69
|
+
const ref = insert(memory.store, project ? 'other-' + project : domain.id, seeded, usage)
|
|
70
|
+
if (!project) { local++; first ??= ref }
|
|
71
|
+
}
|
|
72
|
+
const result = { scenario, total, local }
|
|
73
|
+
const assemble = () => memory.index(agent, domain, true)
|
|
74
|
+
if (usage === 'proactive') {
|
|
75
|
+
result.newTaskIndex = await measure(() => {
|
|
76
|
+
memory.captureTask(agent, { ...message, content: [{ type: 'text', text: message.content[0].text + ' task' + ++taskNumber }] }, 1)
|
|
77
|
+
assert.ok(assemble().included.length)
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
result.index = await measure(assemble)
|
|
81
|
+
result.userStep = await measure(() => hooks.get('agent/pre-step')({ agent, turn: 1, step: 1 },
|
|
82
|
+
async () => ({ kind: 'enter', messages: [message] })))
|
|
83
|
+
result.readById = await measure(async () => assert.equal((await memory.read(agent, first.id, first.rev)).id, first.id))
|
|
84
|
+
result.uniqueKeyword = await measure(async () => assert.equal((await memory.search(agent, 'item000000', 'keyword'))[0]?.id, first.id))
|
|
85
|
+
result.bashChecks = await measure(() => {
|
|
86
|
+
hooks.get('session/event')(session, event)
|
|
87
|
+
assert.equal(hooks.get('guard')(call), undefined)
|
|
88
|
+
})
|
|
89
|
+
result.chatView = await measure(() => memory.view(agent, 'chat'))
|
|
90
|
+
result.exactTopic = await measure(() => assert.equal(memory.store.canonicalTopicHeads(
|
|
91
|
+
domain.id, 'project', 'topicitem000000')[0]?.id, first.id))
|
|
92
|
+
const added = []
|
|
93
|
+
result.commit = await measure(() => added.push(insert(memory.store, domain.id, 1000000 + total * 10 + added.length, usage)))
|
|
94
|
+
result.remember = await measure(() => {
|
|
95
|
+
const seq = events.length
|
|
96
|
+
const commandId = 'remember-' + seq
|
|
97
|
+
events.push({ seq, type: 'command/run', data: { commandId } })
|
|
98
|
+
const action = 'Use changelog convention ' + seq
|
|
99
|
+
const item = { action, user_quote: action, when: '', exceptions: '', paths: [], conflicts_with_repo_guidance: false }
|
|
100
|
+
const receipt = memory.manual(agent, { turnId: 1, userAuthored: true, items: [item] }, commandId)
|
|
101
|
+
assert.equal(receipt.status, 'saved')
|
|
102
|
+
added.push(receipt.entries[0])
|
|
103
|
+
})
|
|
104
|
+
for (const ref of added) memory.store.revoke(domain.id, ref.id, ref.rev, 'seed')
|
|
105
|
+
console.log(JSON.stringify(result))
|
|
106
|
+
}
|
|
107
|
+
} finally {
|
|
108
|
+
memory.retrieval.close()
|
|
109
|
+
memory.store.close()
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
console.log(JSON.stringify({ node: process.version, cpu: cpus()[0]?.model, repetitions, statistic: 'median', unit: 'ms' }))
|
|
114
|
+
const base = mkdtempSync(join(tmpdir(), 'dsh-memory-scale-'))
|
|
115
|
+
try {
|
|
116
|
+
for (const scenario of ['on_demand', 'proactive', 'distributed']) await run(join(base, scenario), scenario)
|
|
117
|
+
} finally {
|
|
118
|
+
rmSync(base, { recursive: true, force: true })
|
|
119
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Each row is an independent repository convention followed by five user phrasings.
|
|
2
|
+
// Recipe names are opaque so a model cannot infer them from the task's wording.
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
|
|
5
|
+
const cases = [
|
|
6
|
+
['integration', 'Run integration tests before merging application changes', 'Run integration tests', 'Exercise how the services work together', 'Perform the pre-merge integration check', 'Check the interaction between components', 'Test the application end to end'],
|
|
7
|
+
['lint', 'Lint JavaScript source for coding style violations', 'Check JavaScript lint', 'Find coding style violations', 'Apply the static style checker', 'Inspect source formatting conventions', 'Run the linter over our scripts'],
|
|
8
|
+
['types', 'Type check TypeScript without emitting JavaScript', 'Check TypeScript types', 'Look for incompatible type assignments', 'Validate static typing without generating files', 'Check compile-time types', 'Do a no-emit compilation'],
|
|
9
|
+
['license', 'Audit third party dependency licenses', 'Audit dependency licenses', 'Check legal terms for bundled libraries', 'Inspect third party license compliance', 'Check the licenses of transitive dependencies', 'Review permissions on vendored packages'],
|
|
10
|
+
['changelog', 'Generate release notes from user visible changes', 'Generate release notes', 'Summarize changes for our users', 'Build the changelog for this release', 'Prepare the customer-facing update history', 'Write up what shipped'],
|
|
11
|
+
['database', 'Test database migrations against a clean SQLite database', 'Test the SQLite migration', 'Try upgrading the schema on a blank database', 'Validate database migration scripts', 'Exercise the schema change on an empty store', 'Check fresh database upgrades'],
|
|
12
|
+
['archive', 'Verify checksum of the release archive', 'Verify the archive checksum', 'Check the integrity of the compressed distribution', 'Validate the package digest', 'Detect corruption in the release tarball', 'Compare the archive hash'],
|
|
13
|
+
['client', 'Regenerate the client SDK from the API definition', 'Regenerate the client SDK', 'Rebuild the consumer library from the service contract', 'Refresh generated API bindings', 'Produce a fresh client from the OpenAPI schema', 'Update the generated service client'],
|
|
14
|
+
['assets', 'Compress static image assets for the website', 'Compress website assets', 'Reduce the bytes of pictures in the site', 'Optimize static images', 'Shrink image downloads for web visitors', 'Minimize the site image payload'],
|
|
15
|
+
['benchmark', 'Measure startup latency of the command line application', 'Measure command line startup latency', 'Time how quickly the CLI becomes ready', 'Benchmark cold launch of the utility', 'Profile executable initialization delay', 'Check time to first prompt'],
|
|
16
|
+
['docs', 'Find broken internal links in the documentation', 'Find broken documentation links', 'Look for dead references in the handbook', 'Check internal links in Markdown pages', 'Verify cross-references throughout the manual', 'Detect missing documentation destinations'],
|
|
17
|
+
['i18n', 'Find missing translation keys in locale dictionaries', 'Find missing translation keys', 'Check that language packs cover the same text', 'Audit locale dictionaries for omissions', 'Look for untranslated interface strings', 'Compare internationalization resources'],
|
|
18
|
+
['formatter', 'Check deterministic formatting of changed source files', 'Check deterministic source formatting', 'Verify touched files would stay unchanged after the formatter', 'Run the formatting check on the patch', 'Look for whitespace drift in modified code', 'Ensure a second formatting pass is clean'],
|
|
19
|
+
['packages', 'Build the distributable npm package and inspect its contents', 'Inspect the npm package contents', 'Check which files users receive from the registry', 'Build and examine the publication tarball', 'List files included in the shipped package', 'Review the archive that goes to npm'],
|
|
20
|
+
['schema', 'Check backward compatibility of the public JSON schema', 'Check backward compatibility of the JSON schema', 'Will existing consumers still accept this new payload shape?', 'Compare the public data contract with its previous version', 'Verify old clients still understand our JSON structure', 'Check API schema compatibility'],
|
|
21
|
+
['locks', 'Check that the lockfile matches the dependency manifest', 'Check the dependency lockfile', 'Confirm installed versions agree with the declared packages', 'Validate the manifest against the lockfile', 'Detect stale resolutions after editing dependencies', 'Compare package declarations to pinned versions'],
|
|
22
|
+
['coverage', '检查变更行的单元测试覆盖率', '检查单元测试覆盖率', '看看本次修改有多少行经过测试', '统计新增代码的覆盖情况', '核对这次变更的测试覆盖', '确认修改的代码都有用例跑到'],
|
|
23
|
+
['snapshot', '更新桌面界面的视觉快照', '更新视觉快照', '重新生成桌面窗口的截图基准', '刷新界面像素比对的参考图', '替换桌面 UI 快照', '更新截图回归使用的底图'],
|
|
24
|
+
['imports', '检查模块之间是否存在循环依赖', '检查循环依赖', '看看模块导入是否绕成了环', '找出相互引用的代码包', '验证依赖图没有闭环', '扫描模块间的循环引用'],
|
|
25
|
+
['symbols', '生成本地调试用的符号表', '生成调试符号表', '让本地崩溃堆栈能解析出函数名', '准备离线调试符号', '导出可执行文件的符号映射', '生成调试器需要的函数索引'],
|
|
26
|
+
['search', '重建开发文档的全文检索索引', '重建全文检索索引', '让新写的开发文档可以被搜到', '刷新文档搜索索引', '重新收录手册里的文字', '更新开发手册的检索库'],
|
|
27
|
+
['timezone', '运行跨时区的日期边界回归测试', '运行跨时区回归', '验证日期切换时在不同时区都正确', '检查午夜附近的日期边界', '测试跨区时间计算', '复核时区切换后的日历行为'],
|
|
28
|
+
['fonts', '核对字体文件覆盖的中文字形', '核对中文字形覆盖', '检查字库里有没有缺字', '验证字体对汉字的支持', '找出中文字体缺失的字形', '确认字体资源能显示所需汉字'],
|
|
29
|
+
['fixtures', '为集成环境生成合成测试数据', '生成合成测试数据', '给集成环境填一些虚构样例', '准备模拟业务记录', '重建用于测试的假数据', '生成集成用的样本记录'],
|
|
30
|
+
['restore', '验证本地备份可以恢复', '验证本地备份恢复', '确认保存的快照能还原出原先的数据', '测试从备份重建存储', '做一次本地恢复演练', '检查留存副本能否还原'],
|
|
31
|
+
['interfaces', '检测公共接口意外增加的导出符号', '检测公共接口导出变化', '看看这次是否意外对外开放了函数', '检查公共模块的符号列表', '比对发布包向使用方暴露的名字', '找出新出现的公开导出项'],
|
|
32
|
+
['ordering', '校准分页查询结果的排序稳定性', '校准分页结果排序', '检查翻页时记录会不会跳位', '验证多页查询的顺序稳定', '同一数据翻页两次能否保持顺序', '复测分页条目的排列'],
|
|
33
|
+
['encoding', '验证文本导入时的字符编码处理', '验证文本导入编码', '检查读取不同字符集时会不会乱码', '测试导入文件的编码识别', '复核多语言文本的解码', '确认非 UTF8 文件也能正确读入'],
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
export const recipe = key => 'make step-' + createHash('sha256').update('recipe-v1:' + key).digest('hex').slice(0, 10)
|
|
37
|
+
const lookup = cases.map(([id, when, ...queries]) => ({ id, repo: 'main', when, queries }))
|
|
38
|
+
const controls = [
|
|
39
|
+
{ id:'corrected', repo:'updated', when:'validate compatibility with the payment provider', revised:true,
|
|
40
|
+
queries:['Validate payment provider compatibility', 'Check whether the billing gateway still works', 'Test the payment integration', 'Verify card processor compatibility', 'Exercise our billing provider contract'] },
|
|
41
|
+
{ id:'neighbor', repo:'neighbor', when:'validate compatibility with the payment provider',
|
|
42
|
+
queries:['Test payment compatibility here', 'Check our billing provider contract', 'Validate the payment gateway', 'Exercise card processor compatibility', 'Run this project’s payment check'] },
|
|
43
|
+
{ id:'withdrawn', repo:'retired', when:'Generate the nightly dependency report', withdrawn:true,
|
|
44
|
+
queries:['Generate the nightly dependency report', 'Prepare the overnight summary of dependencies', 'Update the nightly package report', 'Build the recurring dependency summary', 'Create the overnight library report'] },
|
|
45
|
+
{ id:'missing-target', repo:'branch', when:'校验发布镜像的元数据', absent:true,
|
|
46
|
+
queries:['校验发布镜像元数据', '确认构建镜像的描述信息', '核验发布镜像属性', '检查打包镜像的元信息', '验证交付镜像的元数据'] },
|
|
47
|
+
{ id:'new-repository', repo:'empty', empty:true,
|
|
48
|
+
queries:['Run this repository’s integration check', 'Run our billing test', 'Check release notes here', '执行本项目的文档检查', '检查当前仓库的依赖许可证'] },
|
|
49
|
+
{ id:'standing', repo:'active', when:'Before accepting a release candidate', proactive:true,
|
|
50
|
+
queries:['Validate this release candidate', 'Check this release candidate', 'Run acceptance for the candidate', 'Verify the build before acceptance', 'Perform the release candidate checks'] },
|
|
51
|
+
]
|
|
52
|
+
export const scenarios = [...lookup, ...controls]
|
|
53
|
+
|
|
54
|
+
export function scoreTask(expected, action, receipts) {
|
|
55
|
+
if (expected === null) return !action && receipts.length === 0
|
|
56
|
+
return action === recipe(expected) && receipts.length === 1 && receipts[0] === expected
|
|
57
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { execFileSync, spawnSync } from 'node:child_process'
|
|
4
|
+
import { createRequire } from 'node:module'
|
|
5
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { tmpdir } from 'node:os'
|
|
7
|
+
import { dirname, join, resolve } from 'node:path'
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
9
|
+
import { recipe, scenarios as defaultScenarios, scoreTask } from './benchmark-scenarios.mjs'
|
|
10
|
+
|
|
11
|
+
const script = fileURLToPath(import.meta.url)
|
|
12
|
+
const args = process.argv.slice(2)
|
|
13
|
+
function options(args) {
|
|
14
|
+
const result = { rounds: 5, adapter: join(dirname(script), 'benchmark-bond.mjs') }
|
|
15
|
+
for (let i = 0; i < args.length; i += 2) {
|
|
16
|
+
const [flag, value] = args.slice(i, i + 2)
|
|
17
|
+
if (!['--adapter', '--rounds', '--output'].includes(flag) || !value || value.startsWith('--'))
|
|
18
|
+
throw Error('Expected --adapter PATH, --rounds N or --output FILE')
|
|
19
|
+
if (flag === '--rounds') {
|
|
20
|
+
result.rounds = Number(value)
|
|
21
|
+
if (!Number.isSafeInteger(result.rounds) || result.rounds < 1) throw Error('rounds must be a positive integer')
|
|
22
|
+
} else result[flag.slice(2)] = resolve(value)
|
|
23
|
+
}
|
|
24
|
+
return result
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function initRepository(path, records, removeAbsent = false) {
|
|
28
|
+
if (!existsSync(path)) {
|
|
29
|
+
mkdirSync(path)
|
|
30
|
+
execFileSync('git', ['init','-q','-b','main'], {cwd:path})
|
|
31
|
+
}
|
|
32
|
+
const ids = records.filter(r => !r.empty && !(removeAbsent && r.absent)).flatMap(r => r.revised ? [r.id, r.id+'-old'] : [r.id])
|
|
33
|
+
const names = ids.map(id => recipe(id).slice(5))
|
|
34
|
+
writeFileSync(join(path,'Makefile'), '.PHONY: ' + names.join(' ') + '\n' +
|
|
35
|
+
ids.map((id,i) => names[i] + ':\n\t@printf "%s\\n" ' + id + ' >> .task-actions\n').join(''))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const bytes = text => Buffer.byteLength(text, 'utf8')
|
|
39
|
+
function requestSize(req) {
|
|
40
|
+
const system = req.messages.filter(m => m.role === 'system' && m.source?.kind !== 'runtime-context').flatMap(m => m.content.map(b => b.text ?? '')).join('\n')
|
|
41
|
+
const runtime = req.messages.filter(m => m.source?.kind === 'runtime-context').flatMap(m => m.content.map(b => b.text ?? '')).join('\n')
|
|
42
|
+
const systemText = bytes(system), runtimeText = bytes(runtime), toolsJson = bytes(JSON.stringify(req.tools))
|
|
43
|
+
return { systemText, runtimeText, toolsJson, total: systemText + runtimeText + toolsJson }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function runWorker(tmp, opts) {
|
|
47
|
+
const anchor = process.env.DSH_INSTALL_DIR
|
|
48
|
+
? join(resolve(process.env.DSH_INSTALL_DIR),'package.json')
|
|
49
|
+
: join(process.env.DSH_APP ?? '/Applications/DeepSeek Harness.app','Contents/Resources/app.asar/dsh/package.json')
|
|
50
|
+
const host = createRequire(anchor), pkg = name => host('@deepseek-ai/' + name)
|
|
51
|
+
const ctx = new (pkg('cordis').Context)()
|
|
52
|
+
const { LlmAdapter, createUserMessage } = pkg('dsh-llm')
|
|
53
|
+
const profile = join(tmp,'profile')
|
|
54
|
+
mkdirSync(profile)
|
|
55
|
+
const adapter = (await import(pathToFileURL(opts.adapter))).default
|
|
56
|
+
const scenarios = adapter.scenarios ?? defaultScenarios
|
|
57
|
+
const modes = adapter.modes ?? ['keyword', 'hybrid']
|
|
58
|
+
assert.ok(Array.isArray(modes) && modes.length && new Set(modes).size === modes.length
|
|
59
|
+
&& (modes.every(mode => ['keyword', 'hybrid'].includes(mode)) || (modes.length === 1 && modes[0] === 'default')),
|
|
60
|
+
'Use keyword and/or hybrid, or default alone for a plugin without a selectable search mode')
|
|
61
|
+
const arms = adapter.arms ?? modes.map(mode => ({ name: mode, mode }))
|
|
62
|
+
assert.ok(arms.length && arms.every(a => modes.includes(a.mode)) &&
|
|
63
|
+
new Set(arms.map(a => a.name)).size === arms.length, 'Expected distinct arms with supported search modes')
|
|
64
|
+
const active = new Map()
|
|
65
|
+
const allowed = new Set(scenarios.flatMap(s => [recipe(s.id), ...(s.revised ? [recipe(s.id+'-old')] : [])]))
|
|
66
|
+
class Scripted extends LlmAdapter {
|
|
67
|
+
async resolveModel(provider, id) { return { provider, id, name:id, context:{contextWindow:200_000} } }
|
|
68
|
+
async *stream(req) {
|
|
69
|
+
const turn = active.get(req.sessionId)
|
|
70
|
+
assert.ok(turn && !req.purpose, 'Unexpected background model request')
|
|
71
|
+
turn.requests++
|
|
72
|
+
assert.ok(turn.requests <= 3, 'Scripted policy was re-entered unexpectedly')
|
|
73
|
+
let call
|
|
74
|
+
if (turn.measure) turn.size = requestSize(req)
|
|
75
|
+
else if (turn.requests === 1) {
|
|
76
|
+
const query = req.messages.findLast(m => m.source?.kind === 'user').content.find(b => b.type === 'text').text
|
|
77
|
+
turn.query = query
|
|
78
|
+
const command = adapter.contextualAction?.(req.messages)
|
|
79
|
+
if (command) turn.action = command
|
|
80
|
+
else {
|
|
81
|
+
call = adapter.search?.(query, turn.mode)
|
|
82
|
+
if (call) {
|
|
83
|
+
assert.ok(req.tools.some(t => t.name === call.name), 'Plugin search tool is missing: ' + call.name)
|
|
84
|
+
turn.lookup = true
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
} else if (turn.lookup && turn.requests === 2) {
|
|
88
|
+
const answer = req.messages.findLast(m => m.role === 'tool')
|
|
89
|
+
assert.ok(answer && !answer.isError, 'DSH search tool failed')
|
|
90
|
+
const found = await adapter.result(answer.content.filter(b => b.type === 'text').map(b => b.text).join(''),
|
|
91
|
+
{ query: turn.query, arm: turn.arm })
|
|
92
|
+
turn.action = found.action
|
|
93
|
+
turn.coverage = found.coverage
|
|
94
|
+
turn.decision = found.decision
|
|
95
|
+
}
|
|
96
|
+
if (!call && turn.action && !turn.dispatched) {
|
|
97
|
+
if (!allowed.has(turn.action)) throw Error('Adapter returned an action outside the fixture: '+turn.action)
|
|
98
|
+
turn.dispatched = true
|
|
99
|
+
call = {name:'bash',args:{command:turn.action,description:'Run the selected repository task'}}
|
|
100
|
+
}
|
|
101
|
+
if (call) {
|
|
102
|
+
yield {type:'block-start',index:0,blockType:'tool-call'}
|
|
103
|
+
yield {type:'block-end',index:0,block:{type:'tool-call',id:'call-'+turn.requests,name:call.name,arguments:JSON.stringify(call.args)}}
|
|
104
|
+
yield {type:'finish',reason:{kind:'tool-calls'}}
|
|
105
|
+
} else {
|
|
106
|
+
yield {type:'block-start',index:0,blockType:'text'}
|
|
107
|
+
yield {type:'block-end',index:0,block:{type:'text',text:'Done.'}}
|
|
108
|
+
yield {type:'finish',reason:{kind:'stop'}}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
let serial = 0
|
|
113
|
+
const handle = cwd => ctx.agents.create({sessionId:'trial-'+(++serial),agentOptions:{provider:'local-benchmark',model:'scripted'},meta:{cwd}})
|
|
114
|
+
async function turn(cwd, text, state) {
|
|
115
|
+
const h = await handle(cwd)
|
|
116
|
+
state.requests = 0
|
|
117
|
+
active.set(h.agent.id, state)
|
|
118
|
+
try {
|
|
119
|
+
h.agent.followup(createUserMessage({source:{kind:'user'},content:[{type:'text',text}]}))
|
|
120
|
+
await h.agent.whenIdle()
|
|
121
|
+
const events = h.agent.session.snapshotEvents()
|
|
122
|
+
const end = events.findLast(e => e.type === 'turn/end')
|
|
123
|
+
assert.equal(end?.data.reason.kind,'completed',JSON.stringify(end?.data.reason))
|
|
124
|
+
assert.ok(state.requests)
|
|
125
|
+
if (!state.measure) state.observation = adapter.inspect?.({ events, mode: state.mode, lookup: !!state.lookup, repo: state.repo })
|
|
126
|
+
} finally { active.delete(h.agent.id); await h.dispose() }
|
|
127
|
+
return state
|
|
128
|
+
}
|
|
129
|
+
const repos = new Map()
|
|
130
|
+
for (const s of scenarios) {
|
|
131
|
+
if (!repos.has(s.repo)) repos.set(s.repo, [])
|
|
132
|
+
repos.get(s.repo).push(s)
|
|
133
|
+
}
|
|
134
|
+
for (const [repo, records] of repos) initRepository(join(tmp,repo),records)
|
|
135
|
+
async function empty() {
|
|
136
|
+
const result = {en:[],zh:[]}
|
|
137
|
+
for (let n = 0; n < 5; n++) {
|
|
138
|
+
for (const [lang,text] of [['en','Continue the current task.'],['zh','请继续当前任务。']]) {
|
|
139
|
+
result[lang].push((await turn(join(tmp,'empty'),text,{measure:true})).size)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return result
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
ctx.provide('profileContext',{dir:profile,installAnchor:anchor})
|
|
146
|
+
for (const name of ['dsh-llm','dsh-session','dsh-session-projection','dsh-system-prompt','dsh-tools',
|
|
147
|
+
'dsh-tool-executor-native','dsh-agent','dsh-fs-local','dsh-working-directory','dsh-commands','dsh-token-meter',
|
|
148
|
+
'dsh-subprocess-local','dsh-shell-env','dsh-bash-local','dsh-tool-bash','dsh-agent-loop']) {
|
|
149
|
+
const m=pkg(name)
|
|
150
|
+
await ctx.plugin(m.default ?? m, name === 'dsh-agent-loop' ? {agents:[]} : {})
|
|
151
|
+
}
|
|
152
|
+
ctx.llm.registerAdapter(['local-benchmark'],new Scripted())
|
|
153
|
+
const without = await empty()
|
|
154
|
+
await adapter.mount({ctx,profile,host})
|
|
155
|
+
const enabled = await empty()
|
|
156
|
+
const emptyOverhead = Object.fromEntries(Object.keys(without).map(lang => {
|
|
157
|
+
const samples = enabled[lang].map((size,i) => Object.fromEntries(
|
|
158
|
+
Object.keys(size).map(key => [key,size[key]-without[lang][i][key]])))
|
|
159
|
+
return [lang,{samples,without:without[lang],enabled:enabled[lang]}]
|
|
160
|
+
}))
|
|
161
|
+
for (const [repo, group] of repos) {
|
|
162
|
+
const cwd = join(tmp,repo), h = await handle(cwd)
|
|
163
|
+
try {
|
|
164
|
+
const command = async line => {
|
|
165
|
+
const reply = await ctx.commands.execute(h.agent,line,[],new AbortController().signal)
|
|
166
|
+
assert.equal(reply?.result.kind,'success',reply?.result.text)
|
|
167
|
+
return reply.result.text
|
|
168
|
+
}
|
|
169
|
+
await adapter.seed({ctx,profile,agent:h.agent,cwd,command},group.filter(r => !r.empty).map(r => ({
|
|
170
|
+
when:r.when, action:recipe(r.id), previous:r.revised ? recipe(r.id+'-old') : undefined,
|
|
171
|
+
proactive:!!r.proactive,withdrawn:!!r.withdrawn,
|
|
172
|
+
})))
|
|
173
|
+
} finally { await h.dispose() }
|
|
174
|
+
if (group.some(s => s.absent)) initRepository(cwd,group,true)
|
|
175
|
+
}
|
|
176
|
+
const indexing = await adapter.ready?.({ctx,profile,host})
|
|
177
|
+
const samples = []
|
|
178
|
+
for (let round = 0; round < opts.rounds; round++) {
|
|
179
|
+
for (const [position,s] of scenarios.entries()) {
|
|
180
|
+
const cwd=join(tmp,s.repo), marker=join(cwd,'.task-actions')
|
|
181
|
+
const query = s.queries[round % s.queries.length]
|
|
182
|
+
const expected = s.withdrawn || s.absent || s.empty ? null : s.id
|
|
183
|
+
const pair = {scenario:s.id, round:round+1, query, expected}
|
|
184
|
+
for (const { name, mode } of (round + position) % 2 ? [...arms].reverse() : arms) {
|
|
185
|
+
rmSync(marker,{force:true})
|
|
186
|
+
const result = await turn(cwd,query,{mode,arm:name,repo:s.repo})
|
|
187
|
+
const receipts = existsSync(marker) ? readFileSync(marker,'utf8').trim().split('\n') : []
|
|
188
|
+
const passed = scoreTask(expected, result.action, receipts)
|
|
189
|
+
pair[name] = {passed,action:result.action ?? null,receipts,requests:result.requests,
|
|
190
|
+
...(result.decision && {decision:result.decision}),
|
|
191
|
+
...(result.coverage && {coverage:result.coverage}),
|
|
192
|
+
...(result.observation && {observation:result.observation})}
|
|
193
|
+
}
|
|
194
|
+
samples.push(pair)
|
|
195
|
+
}
|
|
196
|
+
console.error('Completed round '+(round+1)+' / '+opts.rounds)
|
|
197
|
+
}
|
|
198
|
+
function summarize(list) {
|
|
199
|
+
const result = {samples: list.length}
|
|
200
|
+
for (const { name } of arms) {
|
|
201
|
+
const count = list.filter(pair => pair[name].passed).length
|
|
202
|
+
result[name] = count
|
|
203
|
+
result[name + 'Rate'] = count / list.length
|
|
204
|
+
}
|
|
205
|
+
if (arms.some(a => a.name === 'keyword') && arms.some(a => a.name === 'hybrid')) {
|
|
206
|
+
result.differencePoints = 100 * (result.hybrid - result.keyword) / list.length
|
|
207
|
+
result.hybridOnly = list.filter(pair => pair.hybrid.passed && !pair.keyword.passed).length
|
|
208
|
+
result.keywordOnly = list.filter(pair => pair.keyword.passed && !pair.hybrid.passed).length
|
|
209
|
+
}
|
|
210
|
+
return result
|
|
211
|
+
}
|
|
212
|
+
const report = {
|
|
213
|
+
formatVersion: 1, adapter: adapter.name, host: pkg('dsh-agent/package.json').version,
|
|
214
|
+
environment: { node: process.versions.node, platform: process.platform, arch: process.arch }, modes,
|
|
215
|
+
...(adapter.arms && { arms }),
|
|
216
|
+
policy: adapter.policy ?? 'scripted top-one lookup or complete context action; native DSH bash', rounds: opts.rounds,
|
|
217
|
+
scenarios: scenarios.length, indexing, emptyOverhead, totals: summarize(samples),
|
|
218
|
+
byScenario: Object.fromEntries(scenarios.map(s => [s.id, summarize(samples.filter(p => p.scenario === s.id))])),
|
|
219
|
+
samples,
|
|
220
|
+
}
|
|
221
|
+
if (opts.output) writeFileSync(opts.output,JSON.stringify(report,null,2)+'\n')
|
|
222
|
+
console.log(JSON.stringify({adapter:adapter.name,scenarios:scenarios.length,...report.totals,emptyBytes:{
|
|
223
|
+
en:emptyOverhead.en.samples[0].total,zh:emptyOverhead.zh.samples[0].total}}))
|
|
224
|
+
} finally {
|
|
225
|
+
try { await ctx.fiber.dispose() } finally { await adapter.close?.() }
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (args[0] === '--worker') await runWorker(args[1],options(args.slice(2)))
|
|
230
|
+
else {
|
|
231
|
+
options(args)
|
|
232
|
+
const tmp = realpathSync(mkdtempSync(join(tmpdir(),'dsh-task-benchmark-')))
|
|
233
|
+
try {
|
|
234
|
+
const desktop = !process.env.DSH_INSTALL_DIR
|
|
235
|
+
const executable = desktop ? join(process.env.DSH_APP ?? '/Applications/DeepSeek Harness.app','Contents/MacOS/DeepSeek Harness') : process.execPath
|
|
236
|
+
const result = spawnSync(executable,[...(desktop?['--expose-internals']:[]),script,'--worker',tmp,...args],{
|
|
237
|
+
env:{...process.env,...(desktop && {ELECTRON_RUN_AS_NODE:'1'}),HOME:tmp,DSH_HOME:join(tmp,'dsh'),
|
|
238
|
+
DSH_AGENTS_HOME:join(tmp,'agents'),GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',
|
|
239
|
+
DSH_TELEMETRY_DISABLED:'1'},stdio:'inherit',
|
|
240
|
+
})
|
|
241
|
+
if (result.error) throw result.error
|
|
242
|
+
process.exitCode = result.status ?? 1
|
|
243
|
+
} finally {rmSync(tmp,{recursive:true,force:true})}
|
|
244
|
+
}
|