dsh-memvault 0.10.1 → 0.11.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/README.md +60 -24
- package/README.zh.md +70 -34
- package/cordis.patch.yml +23 -0
- package/docs/CORE-DESIGN.md +9 -0
- package/docs/DEVLOG.md +607 -0
- package/docs/PLAN-0.11.md +421 -0
- package/docs/domains/game-dev.md +67 -0
- package/lib/blocks.js +34 -8
- package/lib/client.js +631 -12
- package/lib/config.js +207 -0
- package/lib/core/block-write.js +70 -17
- package/lib/core/host.js +15 -4
- package/lib/core/knowledge.js +332 -0
- package/lib/core/pipeline.js +13 -4
- package/lib/core/promotion.js +155 -0
- package/lib/core/proposals.js +508 -0
- package/lib/core/schema.js +159 -1
- package/lib/core/store.js +160 -3
- package/lib/core/tools.js +155 -4
- package/lib/domain-host.js +490 -0
- package/lib/domain.js +483 -0
- package/lib/gate.js +201 -0
- package/lib/index.js +412 -7
- package/lib/panel.js +209 -3
- package/package.json +1 -1
- package/scripts/seed-domains.mjs +171 -0
- package/scripts/smoke-panel.mjs +200 -14
- package/src/client/index.js +629 -10
package/lib/domain.js
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Domain packs: background knowledge for one vertical, loaded only while it applies.
|
|
3
|
+
*
|
|
4
|
+
* The problem this solves is the one the plan states as P3: a project may need
|
|
5
|
+
* game-engine rules, study-note conventions, modelling pipelines — but injecting
|
|
6
|
+
* all of them would eat the whole 4000-character budget and give the model
|
|
7
|
+
* instructions for work it is not doing. So a pack is split in two:
|
|
8
|
+
*
|
|
9
|
+
* - `index_text` (≤600 chars) goes into the second prompt context while the pack
|
|
10
|
+
* is active: what it is, when it applies, the red lines, and the gate summary.
|
|
11
|
+
* - `detail_text` is never injected; the model reads it with `domain_detail` when
|
|
12
|
+
* it actually needs the detail.
|
|
13
|
+
*
|
|
14
|
+
* Activation is a deterministic score, not a model judgement: the same workspace
|
|
15
|
+
* must select the same pack every time, including in a test with no host at all.
|
|
16
|
+
* False positives are worse than misses — a wrong pack injects wrong rules and
|
|
17
|
+
* silently eats budget — so the threshold is high and file evidence is capped.
|
|
18
|
+
*/
|
|
19
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
20
|
+
import { join } from 'node:path'
|
|
21
|
+
|
|
22
|
+
/** Weights, one line each so they can be argued with. */
|
|
23
|
+
export const DOMAIN_WEIGHTS = {
|
|
24
|
+
/** A path component that names the domain ("games/", "notes/") is strong evidence. */
|
|
25
|
+
path: 0.5,
|
|
26
|
+
/** A marker FILE on disk (project.godot, .uproject) is the strongest single signal. */
|
|
27
|
+
marker: 0.6,
|
|
28
|
+
/**
|
|
29
|
+
* A package dependency ("phaser" in package.json) is weaker than a marker file:
|
|
30
|
+
* a web project can pull a game library for one canvas demo without being a game
|
|
31
|
+
* project. On its own it can only reach the shadow band.
|
|
32
|
+
*/
|
|
33
|
+
dep: 0.35,
|
|
34
|
+
/** Two markers is enough without a path; the cap keeps a mono-repo honest. */
|
|
35
|
+
fileCap: 0.9,
|
|
36
|
+
/** Keywords are weak on their own: three of them still cannot activate a pack. */
|
|
37
|
+
keyword: 0.05,
|
|
38
|
+
keywordCap: 3,
|
|
39
|
+
/** A tool argument naming a domain file is evidence of actual work in it. */
|
|
40
|
+
tool: 0.1,
|
|
41
|
+
toolCap: 2,
|
|
42
|
+
/** A domain used in this workspace before is mildly more likely again. */
|
|
43
|
+
history: 0.1,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Activate at or above this score; show a one-line hint between the two. */
|
|
47
|
+
export const DOMAIN_THRESHOLD = 1.0
|
|
48
|
+
export const DOMAIN_SHADOW_FLOOR = 0.6
|
|
49
|
+
|
|
50
|
+
/** Statuses a pack can be in. Only `active` is injected. */
|
|
51
|
+
export const DOMAIN_STATUSES = ['draft', 'active', 'stale', 'suspended', 'retired']
|
|
52
|
+
|
|
53
|
+
const clamp = (value, min, max) => Math.max(min, Math.min(max, value))
|
|
54
|
+
|
|
55
|
+
/** Parse a JSON column, falling back instead of throwing on a hand-edited row. */
|
|
56
|
+
function json(value, fallback) {
|
|
57
|
+
try {
|
|
58
|
+
const parsed = JSON.parse(String(value ?? ''))
|
|
59
|
+
return parsed ?? fallback
|
|
60
|
+
} catch {
|
|
61
|
+
return fallback
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Store row -> API shape. */
|
|
66
|
+
export function toDomain(row) {
|
|
67
|
+
if (!row) return null
|
|
68
|
+
return {
|
|
69
|
+
domainId: row.domain_id,
|
|
70
|
+
name: row.name,
|
|
71
|
+
version: row.version,
|
|
72
|
+
status: row.status,
|
|
73
|
+
indexText: row.index_text,
|
|
74
|
+
detailText: row.detail_text,
|
|
75
|
+
signals: json(row.signals, {}),
|
|
76
|
+
gates: json(row.gates, []),
|
|
77
|
+
redlines: json(row.redlines, []),
|
|
78
|
+
sources: json(row.sources, []),
|
|
79
|
+
ttlDays: row.ttl_days,
|
|
80
|
+
useCount: row.use_count,
|
|
81
|
+
okCount: row.ok_count,
|
|
82
|
+
lastUsedAt: row.last_used_at,
|
|
83
|
+
checkedAt: row.checked_at,
|
|
84
|
+
approvedBy: row.approved_by,
|
|
85
|
+
approvedAt: row.approved_at,
|
|
86
|
+
createdAt: row.created_at,
|
|
87
|
+
updatedAt: row.updated_at,
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Score one pack against what the workspace looks like right now.
|
|
93
|
+
*
|
|
94
|
+
* @param {object} domain - a row from `toDomain`.
|
|
95
|
+
* @param {object} probe - `{ dir, files, deps, text, tools, seen }`, all optional:
|
|
96
|
+
* `dir` is the workspace path, `files` a list of marker paths that exist,
|
|
97
|
+
* `deps` the package.json text, `text` recent user text, `tools` recent tool
|
|
98
|
+
* arguments, `seen` whether this domain ran here before.
|
|
99
|
+
* @returns `{ domainId, score, reasons }` — reasons are for the panel, so a human
|
|
100
|
+
* can see *why* something was injected instead of trusting a number.
|
|
101
|
+
*/
|
|
102
|
+
export function scoreDomain(domain, probe = {}) {
|
|
103
|
+
const signals = domain.signals ?? {}
|
|
104
|
+
const dir = String(probe.dir ?? '').toLowerCase().replace(/\\/g, '/')
|
|
105
|
+
const files = new Set((probe.files ?? []).map((file) => String(file).toLowerCase().replace(/\\/g, '/')))
|
|
106
|
+
const deps = String(probe.deps ?? '').toLowerCase()
|
|
107
|
+
const text = String(probe.text ?? '').toLowerCase()
|
|
108
|
+
const tools = String(probe.tools ?? '').toLowerCase()
|
|
109
|
+
|
|
110
|
+
const reasons = []
|
|
111
|
+
let score = 0
|
|
112
|
+
|
|
113
|
+
const pathGlobs = (signals.pathGlobs ?? []).map((glob) => String(glob).toLowerCase().replace(/\\/g, '/'))
|
|
114
|
+
const pathHit = dir !== '' && pathGlobs.some((glob) => glob !== '' && dir.includes(glob))
|
|
115
|
+
if (pathHit) {
|
|
116
|
+
score += DOMAIN_WEIGHTS.path
|
|
117
|
+
reasons.push(`path:${pathGlobs.find((glob) => dir.includes(glob))}`)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const markers = (signals.fileMarkers ?? []).map((marker) => String(marker).toLowerCase().replace(/\\/g, '/'))
|
|
121
|
+
const markerHits = markers.filter((marker) => marker !== '' && (
|
|
122
|
+
files.has(marker) || [...files].some((file) => file.endsWith(`/${marker}`))
|
|
123
|
+
))
|
|
124
|
+
// Dependencies count as evidence, but weighted below a marker file: "phaser" in
|
|
125
|
+
// package.json is the same kind of hint as "project.godot" on disk, and a JS game
|
|
126
|
+
// project has no marker file — yet a landing page can also pull three.js.
|
|
127
|
+
const depHits = (signals.deps ?? []).filter((dep) => {
|
|
128
|
+
const needle = String(dep).toLowerCase()
|
|
129
|
+
return needle !== '' && deps.includes(needle)
|
|
130
|
+
})
|
|
131
|
+
const fileScore = Math.min(
|
|
132
|
+
markerHits.length * DOMAIN_WEIGHTS.marker + depHits.length * DOMAIN_WEIGHTS.dep,
|
|
133
|
+
DOMAIN_WEIGHTS.fileCap,
|
|
134
|
+
)
|
|
135
|
+
if (fileScore > 0) {
|
|
136
|
+
score += fileScore
|
|
137
|
+
reasons.push(`file:${[...markerHits, ...depHits].join('+')}`)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const keywords = (signals.keywords ?? []).map((keyword) => String(keyword).toLowerCase())
|
|
141
|
+
const keywordHits = keywords.filter((keyword) => keyword !== '' && (text.includes(keyword) || tools.includes(keyword)))
|
|
142
|
+
score += Math.min(keywordHits.length, DOMAIN_WEIGHTS.keywordCap) * DOMAIN_WEIGHTS.keyword
|
|
143
|
+
if (keywordHits.length > 0) reasons.push(`keyword:${keywordHits.slice(0, 3).join('+')}`)
|
|
144
|
+
|
|
145
|
+
const toolHits = keywords.filter((keyword) => keyword !== '' && tools.includes(keyword))
|
|
146
|
+
score += Math.min(toolHits.length, DOMAIN_WEIGHTS.toolCap) * DOMAIN_WEIGHTS.tool
|
|
147
|
+
if (toolHits.length > 0) reasons.push(`tool:${toolHits.slice(0, 2).join('+')}`)
|
|
148
|
+
|
|
149
|
+
if (probe.seen === true) {
|
|
150
|
+
score += DOMAIN_WEIGHTS.history
|
|
151
|
+
reasons.push('history')
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return { domainId: domain.domainId, score: Math.round(score * 1000) / 1000, reasons }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Score every candidate and sort by score, then by id for determinism. */
|
|
158
|
+
export function rankDomains(domains, probe = {}) {
|
|
159
|
+
return domains
|
|
160
|
+
.map((domain) => scoreDomain(domain, probe))
|
|
161
|
+
.sort((a, b) => (b.score - a.score) || a.domainId.localeCompare(b.domainId))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Decide which packs are active and which are only hinted at.
|
|
166
|
+
*
|
|
167
|
+
* `sticky` is the set already active: a pack stays until explicitly deactivated,
|
|
168
|
+
* because re-deciding every step would make the injected prefix flap and the
|
|
169
|
+
* model would see rules appear and disappear mid-task.
|
|
170
|
+
*/
|
|
171
|
+
export function selectDomains({
|
|
172
|
+
ranked = [],
|
|
173
|
+
sticky = new Set(),
|
|
174
|
+
maxDomains = 2,
|
|
175
|
+
threshold = DOMAIN_THRESHOLD,
|
|
176
|
+
shadowFloor = DOMAIN_SHADOW_FLOOR,
|
|
177
|
+
} = {}) {
|
|
178
|
+
const active = []
|
|
179
|
+
const shadow = []
|
|
180
|
+
for (const entry of ranked) {
|
|
181
|
+
if (sticky.has(entry.domainId) || entry.score >= threshold) active.push(entry)
|
|
182
|
+
else if (entry.score >= shadowFloor) shadow.push(entry)
|
|
183
|
+
if (active.length >= maxDomains) break
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
active: active.slice(0, maxDomains),
|
|
187
|
+
shadow: shadow.slice(0, 1),
|
|
188
|
+
// Anything above the threshold but beyond `maxDomains` is reported, not
|
|
189
|
+
// silently dropped: the panel should be able to say "two more matched".
|
|
190
|
+
overflow: ranked.filter((entry) => entry.score >= threshold && !active.some((a) => a.domainId === entry.domainId)),
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Render the active packs into the second context segment.
|
|
196
|
+
*
|
|
197
|
+
* Hard budget: `maxChars` for the whole segment. The header exists because an
|
|
198
|
+
* unattributed block of rules reads as authoritative; the trailing reminder is
|
|
199
|
+
* the one that keeps a stale pack from being obeyed literally.
|
|
200
|
+
*/
|
|
201
|
+
export function renderDomainIndex(domains, {
|
|
202
|
+
maxChars = 1000,
|
|
203
|
+
indexChars = 480,
|
|
204
|
+
header = 'MemVault domain packs (background for the current workspace; ignore any that does not fit the task):',
|
|
205
|
+
} = {}) {
|
|
206
|
+
if (!domains || domains.length === 0) return ''
|
|
207
|
+
const lines = [header]
|
|
208
|
+
let used = header.length + 1
|
|
209
|
+
let dropped = 0
|
|
210
|
+
for (const domain of domains) {
|
|
211
|
+
const body = String(domain.indexText ?? '').trim().replace(/\s*\n\s*/g, ' ').slice(0, indexChars)
|
|
212
|
+
if (!body) { dropped += 1; continue }
|
|
213
|
+
const line = `- [${domain.domainId}] ${body}`
|
|
214
|
+
if (used + line.length + 1 > maxChars) { dropped += 1; continue }
|
|
215
|
+
lines.push(line)
|
|
216
|
+
used += line.length + 1
|
|
217
|
+
}
|
|
218
|
+
if (lines.length === 1) return ''
|
|
219
|
+
if (dropped > 0) {
|
|
220
|
+
// The note is subject to the same budget as the packs: announcing an omission
|
|
221
|
+
// must not be the reason the segment overruns.
|
|
222
|
+
const note = `(${dropped} more pack(s) omitted to stay within ${maxChars} chars)`
|
|
223
|
+
if (used + note.length + 1 <= maxChars) lines.push(note)
|
|
224
|
+
}
|
|
225
|
+
return lines.join('\n')
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The shadow hint: one line, so a wrong guess costs ~20 tokens, not a pack. */
|
|
229
|
+
export function renderShadow(shadow, { maxChars = 120 } = {}) {
|
|
230
|
+
if (!shadow || shadow.length === 0) return ''
|
|
231
|
+
const text = `Possibly relevant domain: ${shadow[0].domainId}. Call domain_activate if it applies.`
|
|
232
|
+
return text.length > maxChars ? `${text.slice(0, maxChars - 1)}…` : text
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Gather what the workspace looks like, for scoring.
|
|
237
|
+
*
|
|
238
|
+
* Deliberately tiny: a listed marker file either exists or it does not, and
|
|
239
|
+
* `package.json` is read once. No globbing, no directory walk — a probe that costs
|
|
240
|
+
* milliseconds is what makes it affordable to run on a TTL, and a walk of a large
|
|
241
|
+
* repo on every step would be a real cost for a hint.
|
|
242
|
+
*
|
|
243
|
+
* The functions are injected so tests can score against a made-up workspace
|
|
244
|
+
* without touching the disk.
|
|
245
|
+
*
|
|
246
|
+
* @returns `{ dir, files, deps }` — `files` are the markers that exist.
|
|
247
|
+
*/
|
|
248
|
+
export function probeWorkspace({
|
|
249
|
+
dir = '',
|
|
250
|
+
domains = [],
|
|
251
|
+
exists = existsSync,
|
|
252
|
+
readText = (path) => readFileSync(path, 'utf8'),
|
|
253
|
+
joinPath = join,
|
|
254
|
+
} = {}) {
|
|
255
|
+
const empty = { dir: '', files: [], deps: '' }
|
|
256
|
+
if (!dir) return empty
|
|
257
|
+
const markers = new Set()
|
|
258
|
+
for (const domain of domains) {
|
|
259
|
+
for (const marker of (domain.signals?.fileMarkers ?? [])) {
|
|
260
|
+
const text = String(marker ?? '').trim()
|
|
261
|
+
if (text) markers.add(text)
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
const files = []
|
|
265
|
+
for (const marker of markers) {
|
|
266
|
+
try {
|
|
267
|
+
if (exists(joinPath(dir, marker))) files.push(marker)
|
|
268
|
+
} catch {
|
|
269
|
+
// An unreadable marker is "not evidence", not an error.
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
let deps = ''
|
|
273
|
+
try {
|
|
274
|
+
deps = String(readText(joinPath(dir, 'package.json')) ?? '')
|
|
275
|
+
} catch {
|
|
276
|
+
deps = ''
|
|
277
|
+
}
|
|
278
|
+
return { dir, files, deps }
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// ── store access ────────────────────────────────────────────────────────────//
|
|
282
|
+
// Kept here rather than on `CoreStore` because a domain is not a memory: it has
|
|
283
|
+
// its own lifecycle, its own approval, and no relation to the retrieval pipeline.
|
|
284
|
+
|
|
285
|
+
export function listDomains(store, { status = 'all', limit = 50 } = {}) {
|
|
286
|
+
if (!store) throw new Error('listDomains needs a store')
|
|
287
|
+
const where = status === 'all' ? '' : 'WHERE status = ?'
|
|
288
|
+
const rows = store.db.prepare(
|
|
289
|
+
`SELECT * FROM domains ${where} ORDER BY domain_id LIMIT ?`,
|
|
290
|
+
).all(...(where ? [status] : []), clamp(Number(limit) || 50, 1, 200))
|
|
291
|
+
return rows.map(toDomain)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export function getDomain(store, domainId) {
|
|
295
|
+
return toDomain(store.db.prepare('SELECT * FROM domains WHERE domain_id = ?').get(String(domainId ?? '')))
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function logDomainEvent(store, domainId, kind, detail = {}, { now = new Date() } = {}) {
|
|
299
|
+
store.db.prepare('INSERT INTO domain_events (domain_id, kind, detail, at) VALUES (?,?,?,?)')
|
|
300
|
+
.run(String(domainId), String(kind), JSON.stringify(detail ?? {}), (now instanceof Date ? now : new Date(now)).toISOString())
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Create or replace a pack. A human-authored pack may be born `active`; an
|
|
305
|
+
* auto-generated one may not — that check lives in the caller's `proposer`
|
|
306
|
+
* argument, because it is a policy decision and this function only writes.
|
|
307
|
+
*/
|
|
308
|
+
export function upsertDomain(store, input = {}, { now = new Date(), proposer = 'manual' } = {}) {
|
|
309
|
+
const at = (now instanceof Date ? now : new Date(now)).toISOString()
|
|
310
|
+
const domainId = String(input.domain_id ?? input.domainId ?? '').trim().toLowerCase()
|
|
311
|
+
if (!/^[a-z][a-z0-9_-]{1,31}$/.test(domainId)) {
|
|
312
|
+
return { ok: false, status: 400, error: 'domain_id must be 2-32 chars of lowercase letters, digits, _ or -' }
|
|
313
|
+
}
|
|
314
|
+
const indexText = String(input.index_text ?? input.indexText ?? '').trim()
|
|
315
|
+
if (!indexText) return { ok: false, status: 400, error: 'index_text is required: an empty index cannot be injected' }
|
|
316
|
+
if (indexText.length > 600) return { ok: false, status: 400, error: `index_text is ${indexText.length} characters; the limit is 600` }
|
|
317
|
+
|
|
318
|
+
const status = String(input.status ?? 'draft')
|
|
319
|
+
if (!DOMAIN_STATUSES.includes(status)) return { ok: false, status: 400, error: `status must be one of ${DOMAIN_STATUSES.join(' | ')}` }
|
|
320
|
+
// A generated pack may not approve itself. Manual authoring is the approval.
|
|
321
|
+
const effectiveStatus = status === 'active' && proposer !== 'manual' && proposer !== 'panel' ? 'draft' : status
|
|
322
|
+
const sources = Array.isArray(input.sources) ? input.sources.slice(0, 20) : []
|
|
323
|
+
if (effectiveStatus === 'active' && sources.length === 0) {
|
|
324
|
+
return { ok: false, status: 400, error: 'activating a domain needs at least one source' }
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const existing = getDomain(store, domainId)
|
|
328
|
+
const approved = effectiveStatus === 'active'
|
|
329
|
+
? { by: existing?.approvedBy ?? 'human:panel', at: existing?.approvedAt ?? at }
|
|
330
|
+
: { by: null, at: null }
|
|
331
|
+
|
|
332
|
+
store.db.prepare(`
|
|
333
|
+
INSERT INTO domains
|
|
334
|
+
(domain_id, name, version, status, index_text, detail_text, signals, gates, redlines,
|
|
335
|
+
sources, ttl_days, use_count, ok_count, last_used_at, checked_at,
|
|
336
|
+
approved_by, approved_at, created_at, updated_at)
|
|
337
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
338
|
+
ON CONFLICT(domain_id) DO UPDATE SET
|
|
339
|
+
name = excluded.name,
|
|
340
|
+
version = domains.version + 1,
|
|
341
|
+
status = excluded.status,
|
|
342
|
+
index_text = excluded.index_text,
|
|
343
|
+
detail_text = excluded.detail_text,
|
|
344
|
+
signals = excluded.signals,
|
|
345
|
+
gates = excluded.gates,
|
|
346
|
+
redlines = excluded.redlines,
|
|
347
|
+
sources = excluded.sources,
|
|
348
|
+
ttl_days = excluded.ttl_days,
|
|
349
|
+
checked_at = excluded.checked_at,
|
|
350
|
+
approved_by = COALESCE(excluded.approved_by, domains.approved_by),
|
|
351
|
+
approved_at = COALESCE(excluded.approved_at, domains.approved_at),
|
|
352
|
+
updated_at = excluded.updated_at
|
|
353
|
+
`).run(
|
|
354
|
+
domainId,
|
|
355
|
+
String(input.name ?? domainId),
|
|
356
|
+
Number(input.version ?? 1) || 1,
|
|
357
|
+
effectiveStatus,
|
|
358
|
+
indexText,
|
|
359
|
+
String(input.detail_text ?? input.detailText ?? '').slice(0, 20000),
|
|
360
|
+
JSON.stringify(input.signals ?? {}),
|
|
361
|
+
JSON.stringify(Array.isArray(input.gates) ? input.gates.slice(0, 10) : []),
|
|
362
|
+
JSON.stringify(Array.isArray(input.redlines) ? input.redlines.slice(0, 20) : []),
|
|
363
|
+
JSON.stringify(sources),
|
|
364
|
+
clamp(Number(input.ttl_days ?? input.ttlDays ?? 90) || 90, 1, 3650),
|
|
365
|
+
0, 0, null,
|
|
366
|
+
at,
|
|
367
|
+
approved.by,
|
|
368
|
+
approved.at,
|
|
369
|
+
existing?.createdAt ?? at,
|
|
370
|
+
at,
|
|
371
|
+
)
|
|
372
|
+
logDomainEvent(store, domainId, effectiveStatus === 'active' ? 'approve' : 'upsert', { version: existing?.version ?? 1, proposer }, { now })
|
|
373
|
+
return { ok: true, status: 200, domain: getDomain(store, domainId) }
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Tool-drafted packs.
|
|
378
|
+
*
|
|
379
|
+
* Two rules make this safe to expose to a model. It can only write `draft`, because
|
|
380
|
+
* `upsertDomain` downgrades an `active` request from a non-human proposer — an
|
|
381
|
+
* extractor that could self-approve would make the human veto decorative. And every
|
|
382
|
+
* draft needs at least one source a person can open or look up: four invented packs
|
|
383
|
+
* had to be deleted because they had none, and a draft without provenance is a guess
|
|
384
|
+
* wearing a rule's clothes.
|
|
385
|
+
*/
|
|
386
|
+
export const DRAFT_LIMITS = {
|
|
387
|
+
/** How many packs may sit on the shelf before drafting is refused. */
|
|
388
|
+
maxPacks: 20,
|
|
389
|
+
maxIndexChars: 600,
|
|
390
|
+
maxDetailChars: 20_000,
|
|
391
|
+
maxSources: 20,
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Create or update a pack as a draft.
|
|
396
|
+
*
|
|
397
|
+
* @returns `{ ok, status, error?, domain?, note? }`.
|
|
398
|
+
*/
|
|
399
|
+
export function draftDomain(store, input = {}, { now = new Date(), maxPacks = DRAFT_LIMITS.maxPacks } = {}) {
|
|
400
|
+
const domainId = String(input.domain_id ?? input.domainId ?? '').trim().toLowerCase()
|
|
401
|
+
if (!/^[a-z][a-z0-9_-]{1,31}$/.test(domainId)) {
|
|
402
|
+
return { ok: false, status: 400, error: 'domain_id must be 2-32 chars of lowercase letters, digits, _ or -' }
|
|
403
|
+
}
|
|
404
|
+
const existing = getDomain(store, domainId)
|
|
405
|
+
if (existing && existing.status === 'active') {
|
|
406
|
+
return {
|
|
407
|
+
ok: false,
|
|
408
|
+
status: 409,
|
|
409
|
+
// Overwriting an approved pack would let the tool change injected rules
|
|
410
|
+
// between two human reviews. Suspending it is the human's move, not the tool's.
|
|
411
|
+
error: `${domainId} is already approved (active); a tool may not rewrite an approved pack. Ask a human to suspend it first.`,
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const sources = Array.isArray(input.sources) ? input.sources.slice(0, DRAFT_LIMITS.maxSources) : []
|
|
416
|
+
const usable = sources
|
|
417
|
+
.map((source) => ({
|
|
418
|
+
title: String(source?.title ?? '').trim().slice(0, 200),
|
|
419
|
+
url: String(source?.url ?? '').trim().slice(0, 500),
|
|
420
|
+
quote: String(source?.quote ?? '').trim().slice(0, 300),
|
|
421
|
+
}))
|
|
422
|
+
.filter((source) => source.title || source.url)
|
|
423
|
+
if (usable.length === 0) {
|
|
424
|
+
return { ok: false, status: 400, error: 'a draft needs at least one source (session id, url, or document title) so a human can check it' }
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
if (!existing) {
|
|
428
|
+
const count = store.db.prepare('SELECT COUNT(*) AS n FROM domains').get()?.n ?? 0
|
|
429
|
+
if (count >= maxPacks) {
|
|
430
|
+
return { ok: false, status: 429, error: `the draft shelf is full (${count}/${maxPacks}); ask a human to review what is there` }
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const result = upsertDomain(store, {
|
|
435
|
+
...input,
|
|
436
|
+
domain_id: domainId,
|
|
437
|
+
status: 'draft',
|
|
438
|
+
sources: usable,
|
|
439
|
+
}, { now, proposer: 'extract' })
|
|
440
|
+
if (!result.ok) return result
|
|
441
|
+
|
|
442
|
+
logDomainEvent(store, domainId, 'draft', { tool: 'domain_draft', sources: usable.length }, { now })
|
|
443
|
+
return {
|
|
444
|
+
...result,
|
|
445
|
+
note: 'saved as a draft; a human must approve it before any of it is injected',
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Move a pack between statuses. Suspending must take effect immediately. */
|
|
450
|
+
export function setDomainStatus(store, domainId, status, { now = new Date(), note = '' } = {}) {
|
|
451
|
+
if (!DOMAIN_STATUSES.includes(status)) {
|
|
452
|
+
return { ok: false, status: 400, error: `status must be one of ${DOMAIN_STATUSES.join(' | ')}` }
|
|
453
|
+
}
|
|
454
|
+
const domain = getDomain(store, domainId)
|
|
455
|
+
if (!domain) return { ok: false, status: 404, error: `no domain ${domainId}` }
|
|
456
|
+
if (status === 'active' && domain.sources.length === 0) {
|
|
457
|
+
return { ok: false, status: 400, error: 'activating a domain needs at least one source' }
|
|
458
|
+
}
|
|
459
|
+
const at = (now instanceof Date ? now : new Date(now)).toISOString()
|
|
460
|
+
// SQLite binds numbers and strings, not booleans — pass 1/0 for the CASE arms.
|
|
461
|
+
const activate = status === 'active' ? 1 : 0
|
|
462
|
+
store.db.prepare(
|
|
463
|
+
`UPDATE domains SET
|
|
464
|
+
status = ?, updated_at = ?,
|
|
465
|
+
checked_at = CASE WHEN ? THEN ? ELSE checked_at END,
|
|
466
|
+
approved_by = CASE WHEN ? THEN ? ELSE approved_by END,
|
|
467
|
+
approved_at = CASE WHEN ? THEN ? ELSE approved_at END
|
|
468
|
+
WHERE domain_id = ?`,
|
|
469
|
+
).run(status, at, activate, at, activate, 'human:panel', activate, at, String(domainId))
|
|
470
|
+
logDomainEvent(store, domainId, status === 'active' ? 'approve' : status, { note }, { now })
|
|
471
|
+
return { ok: true, status: 200, domain: getDomain(store, domainId) }
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Mark usage. A pack that keeps being activated but never helps is exactly what
|
|
476
|
+
* `stale` exists for, so the counter has to be written by the activation path.
|
|
477
|
+
*/
|
|
478
|
+
export function touchDomain(store, domainId, { ok = true, now = new Date() } = {}) {
|
|
479
|
+
const at = (now instanceof Date ? now : new Date(now)).toISOString()
|
|
480
|
+
store.db.prepare(
|
|
481
|
+
'UPDATE domains SET use_count = use_count + 1, ok_count = ok_count + ?, last_used_at = ?, updated_at = ? WHERE domain_id = ?',
|
|
482
|
+
).run(ok ? 1 : 0, at, at, String(domainId))
|
|
483
|
+
}
|
package/lib/gate.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Domain gates: the one mechanism in this plugin that can actually stop a call.
|
|
3
|
+
*
|
|
4
|
+
* A gate is a precondition a pack declares for action tools — "look up the current
|
|
5
|
+
* engine API before writing gameplay code" — and the model satisfies it by calling
|
|
6
|
+
* `domain_gate` with a URL and a verbatim quote. The plugin then refuses the action
|
|
7
|
+
* tools until that gate is satisfied.
|
|
8
|
+
*
|
|
9
|
+
* Why this is not just another prompt line: measured against the real failure the
|
|
10
|
+
* user described ("先搜一下" in the prompt, then the model implements anyway), a
|
|
11
|
+
* sentence competes with every other sentence. A guard runs in the tool pipeline
|
|
12
|
+
* after policy and approval, its denial is fed back as an **error result**, and the
|
|
13
|
+
* model cannot proceed by ignoring it — only by satisfying the gate.
|
|
14
|
+
*
|
|
15
|
+
* What it cannot do, stated here so nobody over-claims it: block a model that
|
|
16
|
+
* answers without calling a tool, or that writes files through a path we do not
|
|
17
|
+
* recognise as a write (a shell variant, a PTC script). The honest ceiling is
|
|
18
|
+
* "tool-layer enforcement plus a visible gate state", which is what this file is.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** Tools refused while a gate is open. Configurable; these are the shipped default. */
|
|
22
|
+
export const DEFAULT_GATED_TOOLS = ['write', 'edit', 'apply_patch', 'memory_add']
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Shell writes we recognise. A guarded `bash` is only refused when the command
|
|
26
|
+
* looks like a write; `ls`, `git status` and `rg` must keep working, or the gate
|
|
27
|
+
* would block the very research it is asking for.
|
|
28
|
+
*
|
|
29
|
+
* Kept as regex sources so the reason string can name what matched.
|
|
30
|
+
*/
|
|
31
|
+
export const DEFAULT_BASH_WRITE_PATTERNS = [
|
|
32
|
+
String.raw`>>?\s*\S`, // redirection
|
|
33
|
+
String.raw`\btee\b`,
|
|
34
|
+
String.raw`\b(Set-Content|Add-Content|Out-File|Set-Item|New-Item|Remove-Item)\b`,
|
|
35
|
+
String.raw`\b(rm|mv|cp|mkdir|touch)\s`,
|
|
36
|
+
String.raw`\bsed\s+-i\b`,
|
|
37
|
+
String.raw`\bnpm\s+(install|i|add)\b`,
|
|
38
|
+
String.raw`\bgit\s+(commit|push|merge|rebase)\b`,
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
/** How long a piece of evidence counts as fresh. */
|
|
42
|
+
export const DEFAULT_MAX_AGE_HOURS = 24
|
|
43
|
+
|
|
44
|
+
/** Shortest acceptable quote: long enough that it had to come from a document. */
|
|
45
|
+
export const DEFAULT_MIN_QUOTE = 40
|
|
46
|
+
|
|
47
|
+
const clampInt = (value, min, max, fallback) => {
|
|
48
|
+
const number = Number(value)
|
|
49
|
+
if (!Number.isFinite(number)) return fallback
|
|
50
|
+
return Math.max(min, Math.min(max, Math.round(number)))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Identity of one gate on one pack version; a new version voids old passes. */
|
|
54
|
+
export function gateKey(domainId, gateId, version) {
|
|
55
|
+
return `${domainId}::${gateId}::${version ?? 0}`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Is this URL something a human could go and check? */
|
|
59
|
+
export function isCheckableUrl(value) {
|
|
60
|
+
const text = String(value ?? '').trim()
|
|
61
|
+
if (text.length < 12) return false
|
|
62
|
+
try {
|
|
63
|
+
const url = new URL(text)
|
|
64
|
+
return url.protocol === 'https:' || url.protocol === 'http:'
|
|
65
|
+
} catch {
|
|
66
|
+
return false
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Does this call count as an action for gate purposes?
|
|
72
|
+
*
|
|
73
|
+
* `write`/`edit`/`apply_patch` are obvious. `bash` is conditional: a shell command
|
|
74
|
+
* that only reads is research, not the thing the gate is protecting.
|
|
75
|
+
*/
|
|
76
|
+
export function isActionTool(name, args, {
|
|
77
|
+
tools = DEFAULT_GATED_TOOLS,
|
|
78
|
+
bashWritePatterns = DEFAULT_BASH_WRITE_PATTERNS,
|
|
79
|
+
blockBashWrites = true,
|
|
80
|
+
} = {}) {
|
|
81
|
+
const tool = String(name ?? '')
|
|
82
|
+
if (tools.includes(tool)) return true
|
|
83
|
+
if (!blockBashWrites) return false
|
|
84
|
+
if (tool !== 'bash') return false
|
|
85
|
+
const command = typeof args === 'string'
|
|
86
|
+
? args
|
|
87
|
+
: String(args?.command ?? args?.cmd ?? args?.script ?? '')
|
|
88
|
+
if (!command) return false
|
|
89
|
+
return bashWritePatterns.some((pattern) => {
|
|
90
|
+
try {
|
|
91
|
+
return new RegExp(pattern, 'i').test(command)
|
|
92
|
+
} catch {
|
|
93
|
+
return false
|
|
94
|
+
}
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Validate one piece of gate evidence.
|
|
100
|
+
*
|
|
101
|
+
* Server-side shape checks only: no network request is made, so "the URL resolves"
|
|
102
|
+
* is not claimed. What is checked is the part a model can fail honestly — a scheme,
|
|
103
|
+
* a quote long enough to have come from a page, and a timestamp that is not stale.
|
|
104
|
+
*
|
|
105
|
+
* @returns `{ ok, reason }`.
|
|
106
|
+
*/
|
|
107
|
+
export function evaluateEvidence(gate = {}, evidence = {}, {
|
|
108
|
+
now = Date.now(),
|
|
109
|
+
maxAgeHours = DEFAULT_MAX_AGE_HOURS,
|
|
110
|
+
minQuote = DEFAULT_MIN_QUOTE,
|
|
111
|
+
} = {}) {
|
|
112
|
+
const spec = gate.evidence ?? {}
|
|
113
|
+
const requireUrl = spec.requireUrl !== false
|
|
114
|
+
const requiredQuote = clampInt(spec.minQuote ?? minQuote, 0, 4000, minQuote)
|
|
115
|
+
const maxAge = clampInt(spec.maxAgeHours ?? maxAgeHours, 1, 24 * 365, maxAgeHours)
|
|
116
|
+
|
|
117
|
+
const url = String(evidence.url ?? '').trim()
|
|
118
|
+
const quote = String(evidence.quote ?? '').trim()
|
|
119
|
+
if (requireUrl && !isCheckableUrl(url)) {
|
|
120
|
+
return { ok: false, reason: 'evidence needs an http(s) url that a human could open' }
|
|
121
|
+
}
|
|
122
|
+
if (quote.length < requiredQuote) {
|
|
123
|
+
return { ok: false, reason: `the quote is ${quote.length} characters; at least ${requiredQuote} are required so it had to come from a document` }
|
|
124
|
+
}
|
|
125
|
+
const verifiedAt = Number.isFinite(Number(evidence.verifiedAt)) ? Number(evidence.verifiedAt) : now
|
|
126
|
+
if (now - verifiedAt > maxAge * 3600_000) {
|
|
127
|
+
return { ok: false, reason: `that verification is older than ${maxAge}h; re-check the source` }
|
|
128
|
+
}
|
|
129
|
+
if (verifiedAt - now > 3600_000) {
|
|
130
|
+
return { ok: false, reason: 'the verification timestamp is in the future' }
|
|
131
|
+
}
|
|
132
|
+
return { ok: true, reason: null }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Every gate that is still open on a set of active packs.
|
|
137
|
+
*
|
|
138
|
+
* Only `active` packs reach this function (the caller filters), and `stale` packs
|
|
139
|
+
* are skipped on purpose: an out-of-date rule must not be able to hold work
|
|
140
|
+
* hostage. That downgrade is the same one the domain segment makes.
|
|
141
|
+
*
|
|
142
|
+
* @returns `Array<{ domainId, domainName, version, gateId, text, blocks }>`.
|
|
143
|
+
*/
|
|
144
|
+
export function openGates(domains, passed, { logger = null } = {}) {
|
|
145
|
+
const open = []
|
|
146
|
+
for (const domain of domains ?? []) {
|
|
147
|
+
if (!domain || domain.status !== 'active') continue
|
|
148
|
+
for (const gate of domain.gates ?? []) {
|
|
149
|
+
const gateId = String(gate?.id ?? '').trim()
|
|
150
|
+
if (!gateId) continue
|
|
151
|
+
if (passed && passed.has(gateKey(domain.domainId, gateId, domain.version))) continue
|
|
152
|
+
open.push({
|
|
153
|
+
domainId: domain.domainId,
|
|
154
|
+
domainName: domain.name ?? domain.domainId,
|
|
155
|
+
version: domain.version ?? 0,
|
|
156
|
+
gateId,
|
|
157
|
+
text: String(gate.text ?? gateId),
|
|
158
|
+
blocks: Array.isArray(gate.blocks) && gate.blocks.length > 0 ? gate.blocks : null,
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (logger) logger.debug?.(`dsh-memvault: ${open.length} domain gate(s) open`)
|
|
163
|
+
return open
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The guard itself: synchronous, no I/O, no await — the pipeline calls it inline.
|
|
168
|
+
*
|
|
169
|
+
* State comes from the domain host, refreshed when the segment is computed. If the
|
|
170
|
+
* state is cold (nothing computed yet) this allows the call: refusing work because
|
|
171
|
+
* a cache is empty would be a worse failure than a missed gate, and the next step
|
|
172
|
+
* computes the segment anyway.
|
|
173
|
+
*
|
|
174
|
+
* @returns `undefined` to allow, or a reason string that is rendered as an error
|
|
175
|
+
* result. The reason is an instruction, not a prohibition: a blocked model that
|
|
176
|
+
* does not know what to do next will simply retry.
|
|
177
|
+
*/
|
|
178
|
+
export function gateGuard(exec, { state, config = {}, now = Date.now() } = {}) {
|
|
179
|
+
if (!state) return undefined
|
|
180
|
+
const gates = Array.isArray(state.openGates) ? state.openGates : []
|
|
181
|
+
if (gates.length === 0) return undefined
|
|
182
|
+
|
|
183
|
+
const tool = String(exec?.name ?? '')
|
|
184
|
+
const gatesForTool = gates.filter((gate) => !gate.blocks || gate.blocks.includes(tool))
|
|
185
|
+
if (gatesForTool.length === 0) return undefined
|
|
186
|
+
if (!isActionTool(tool, exec?.arguments, config)) return undefined
|
|
187
|
+
|
|
188
|
+
const blocker = gatesForTool[0]
|
|
189
|
+
const extra = gatesForTool.length > 1 ? ` (${gatesForTool.length - 1} more gate(s) also open)` : ''
|
|
190
|
+
return `domain gate not satisfied for [${blocker.domainId}]: ${blocker.text}.`
|
|
191
|
+
+ ` Call domain_gate with domain_id="${blocker.domainId}", gate_id="${blocker.gateId}",`
|
|
192
|
+
+ ` url="<the document you read>" and quote="<at least 40 characters copied from it>", then retry ${tool}.${extra}`
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The one-line notice appended to the domain segment while a gate is open. */
|
|
196
|
+
export function renderGateNotice(gates, { maxChars = 240 } = {}) {
|
|
197
|
+
if (!gates || gates.length === 0) return ''
|
|
198
|
+
const first = gates[0]
|
|
199
|
+
const text = `GATE OPEN [${first.domainId}/${first.gateId}]: ${first.text} — action tools are refused until you call domain_gate with a url and a quote.`
|
|
200
|
+
return text.length > maxChars ? `${text.slice(0, maxChars - 1)}…` : text
|
|
201
|
+
}
|