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
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core-block proposals: the only path by which a block may change without a
|
|
3
|
+
* human typing it.
|
|
4
|
+
*
|
|
5
|
+
* The rule this module exists to enforce is narrow and absolute: **the model can
|
|
6
|
+
* propose, only a human can approve.** There is deliberately no `approve`
|
|
7
|
+
* function reachable from a tool, and `decided_by` only ever holds a `human:` or
|
|
8
|
+
* `system:` prefix — a reviewer reading the table can tell them apart at a glance.
|
|
9
|
+
*
|
|
10
|
+
* Why not reuse `memories`: a proposal is a *patch*, not a fact. Its text must not
|
|
11
|
+
* enter the FTS index (a pending guess would come back from `memory_search` as
|
|
12
|
+
* established truth), and `supersede` semantics describe a fact changing over
|
|
13
|
+
* time, not a candidate waiting for a decision.
|
|
14
|
+
*/
|
|
15
|
+
import { createHash } from 'node:crypto'
|
|
16
|
+
|
|
17
|
+
import { BLOCK_LABEL_MAX, BLOCK_VALUE_MAX, commitBlock, validateBlockAction } from './block-write.js'
|
|
18
|
+
|
|
19
|
+
/** Change kinds a proposal may carry. `merge` waits for a later phase. */
|
|
20
|
+
export const PROPOSAL_KINDS = ['create', 'rewrite', 'delete']
|
|
21
|
+
|
|
22
|
+
/** Every status the table accepts. */
|
|
23
|
+
export const PROPOSAL_STATUSES = [
|
|
24
|
+
'pending', 'stale', 'approved', 'applied', 'rolled_back', 'rejected', 'expired',
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
/** Decisions a human may take through the panel. */
|
|
28
|
+
export const PROPOSAL_ACTIONS = ['approve', 'reject', 'rollback']
|
|
29
|
+
|
|
30
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Anti-spam defaults.
|
|
34
|
+
*
|
|
35
|
+
* The numbers are not guesses about taste — each one answers "what does the panel
|
|
36
|
+
* look like when it goes wrong". Two pending proposals for one block is the most
|
|
37
|
+
* a person will actually compare before clicking whichever is first; four a day
|
|
38
|
+
* matches the extraction cadence (every third turn) so one busy conversation
|
|
39
|
+
* cannot exhaust it; twelve a day keeps a freshly enabled extractor from turning
|
|
40
|
+
* the queue into a wall.
|
|
41
|
+
*/
|
|
42
|
+
export const PROPOSAL_LIMITS = {
|
|
43
|
+
perBlockPending: 2,
|
|
44
|
+
perBlockPerDay: 4,
|
|
45
|
+
globalPerDay: 12,
|
|
46
|
+
/** Rejections of the same target inside this window arm the cooldown… */
|
|
47
|
+
rejectWindowDays: 14,
|
|
48
|
+
/** …for this long. "Said no twice" means the signal itself is wrong. */
|
|
49
|
+
rejectCooldownDays: 7,
|
|
50
|
+
rejectionsToCool: 2,
|
|
51
|
+
pendingTtlDays: 14,
|
|
52
|
+
/** A pending proposal whose value is this close to the current one is a no-op. */
|
|
53
|
+
noOpSimilarity: 0.95,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Normalize text for dedupe: whitespace collapsed, case folded, trimmed. */
|
|
57
|
+
function normalize(value) {
|
|
58
|
+
return String(value ?? '').replace(/\s+/g, ' ').trim().toLowerCase()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Bigram Jaccard similarity, copied in behaviour from `decide.js` so the two
|
|
63
|
+
* "is this the same statement" judgements in the plugin agree.
|
|
64
|
+
*/
|
|
65
|
+
export function similarity(a, b) {
|
|
66
|
+
const left = normalize(a)
|
|
67
|
+
const right = normalize(b)
|
|
68
|
+
if (!left || !right) return 0
|
|
69
|
+
if (left === right) return 1
|
|
70
|
+
const grams = (text) => {
|
|
71
|
+
const set = new Set()
|
|
72
|
+
const chars = [...text]
|
|
73
|
+
for (let i = 0; i < chars.length - 1; i += 1) set.add(chars[i] + chars[i + 1])
|
|
74
|
+
return set
|
|
75
|
+
}
|
|
76
|
+
const leftGrams = grams(left)
|
|
77
|
+
const rightGrams = grams(right)
|
|
78
|
+
if (leftGrams.size === 0 || rightGrams.size === 0) return 0
|
|
79
|
+
let shared = 0
|
|
80
|
+
for (const gram of leftGrams) if (rightGrams.has(gram)) shared += 1
|
|
81
|
+
return shared / (leftGrams.size + rightGrams.size - shared)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Stable identity of a proposal, so the same patch cannot be queued twice. */
|
|
85
|
+
export function proposalDedupeKey({ scopeType, scopeId, label, changeKind, value }) {
|
|
86
|
+
return createHash('sha1')
|
|
87
|
+
.update([scopeType, scopeId, label, changeKind, normalize(value)].join('\u0000'))
|
|
88
|
+
.digest('hex')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Validate a proposal request; mirrors the block writer's limits on purpose. */
|
|
92
|
+
export function validateProposal(input = {}) {
|
|
93
|
+
const scopeType = String(input?.scope_type ?? input?.scopeType ?? '').trim()
|
|
94
|
+
if (scopeType !== 'user' && scopeType !== 'agent') return { ok: false, error: 'scope_type must be user or agent' }
|
|
95
|
+
const scopeId = String(input?.scope_id ?? input?.scopeId ?? '').trim()
|
|
96
|
+
if (!scopeId) return { ok: false, error: 'scope_id is required' }
|
|
97
|
+
if (scopeId.length > 200) return { ok: false, error: 'scope_id is longer than 200 characters' }
|
|
98
|
+
|
|
99
|
+
const label = String(input?.label ?? '').trim()
|
|
100
|
+
if (!label) return { ok: false, error: 'label is required' }
|
|
101
|
+
if (label.length > BLOCK_LABEL_MAX) return { ok: false, error: `label is longer than ${BLOCK_LABEL_MAX} characters` }
|
|
102
|
+
if (/[\r\n]/.test(label)) return { ok: false, error: 'label must be a single line' }
|
|
103
|
+
|
|
104
|
+
const changeKind = String(input?.change_kind ?? input?.changeKind ?? 'rewrite').trim()
|
|
105
|
+
if (!PROPOSAL_KINDS.includes(changeKind)) return { ok: false, error: `change_kind must be one of ${PROPOSAL_KINDS.join(' | ')}` }
|
|
106
|
+
|
|
107
|
+
const value = input?.value === undefined || input?.value === null ? '' : String(input.value)
|
|
108
|
+
if (changeKind === 'delete') {
|
|
109
|
+
if (value !== '') return { ok: false, error: 'delete proposals take no value' }
|
|
110
|
+
} else {
|
|
111
|
+
// Reuse the block writer's own rules so a proposal that would be rejected at
|
|
112
|
+
// approval time is rejected at proposal time instead — the human should never
|
|
113
|
+
// approve something the writer will refuse.
|
|
114
|
+
const asWrite = validateBlockAction({ action: 'set', type: scopeType, id: scopeId, label, value })
|
|
115
|
+
if (!asWrite.ok) return { ok: false, error: asWrite.error }
|
|
116
|
+
}
|
|
117
|
+
if (value.length > BLOCK_VALUE_MAX) return { ok: false, error: `value is longer than ${BLOCK_VALUE_MAX} characters` }
|
|
118
|
+
|
|
119
|
+
let confidence = input?.confidence === undefined || input?.confidence === null ? null : Number(input.confidence)
|
|
120
|
+
if (confidence !== null && (!Number.isFinite(confidence) || confidence < 0 || confidence > 1)) {
|
|
121
|
+
return { ok: false, error: 'confidence must be between 0 and 1' }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const proposer = String(input?.proposer ?? 'extract').trim()
|
|
125
|
+
if (!['extract', 'manual', 'panel'].includes(proposer)) return { ok: false, error: 'proposer must be extract, manual or panel' }
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
ok: true,
|
|
129
|
+
scopeType,
|
|
130
|
+
scopeId,
|
|
131
|
+
label,
|
|
132
|
+
changeKind,
|
|
133
|
+
value,
|
|
134
|
+
confidence: confidence ?? (proposer === 'extract' ? 0.6 : 1),
|
|
135
|
+
proposer,
|
|
136
|
+
evidence: Array.isArray(input?.evidence) ? input.evidence.slice(0, 5) : [],
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function rowToProposal(row) {
|
|
141
|
+
if (!row) return null
|
|
142
|
+
return {
|
|
143
|
+
id: row.id,
|
|
144
|
+
scopeType: row.scope_type,
|
|
145
|
+
scopeId: row.scope_id,
|
|
146
|
+
label: row.label,
|
|
147
|
+
changeKind: row.change_kind,
|
|
148
|
+
baseValue: row.base_value,
|
|
149
|
+
baseUpdatedAt: row.base_updated_at,
|
|
150
|
+
proposedValue: row.proposed_value,
|
|
151
|
+
evidence: safeJson(row.evidence, []),
|
|
152
|
+
confidence: row.confidence,
|
|
153
|
+
proposer: row.proposer,
|
|
154
|
+
status: row.status,
|
|
155
|
+
dedupeKey: row.dedupe_key,
|
|
156
|
+
createdAt: row.created_at,
|
|
157
|
+
updatedAt: row.updated_at,
|
|
158
|
+
expiresAt: row.expires_at,
|
|
159
|
+
decidedBy: row.decided_by,
|
|
160
|
+
decidedAt: row.decided_at,
|
|
161
|
+
decisionNote: row.decision_note,
|
|
162
|
+
appliedAt: row.applied_at,
|
|
163
|
+
appliedValue: row.applied_value,
|
|
164
|
+
rolledBackAt: row.rolled_back_at,
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function safeJson(text, fallback) {
|
|
169
|
+
try {
|
|
170
|
+
const parsed = JSON.parse(String(text ?? ''))
|
|
171
|
+
return parsed ?? fallback
|
|
172
|
+
} catch {
|
|
173
|
+
return fallback
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function blockRowToSnapshot(row) {
|
|
178
|
+
if (!row) return null
|
|
179
|
+
return {
|
|
180
|
+
scopeType: row.scope_type,
|
|
181
|
+
scopeId: row.scope_id,
|
|
182
|
+
label: row.label,
|
|
183
|
+
value: row.value,
|
|
184
|
+
valueLimit: row.value_limit,
|
|
185
|
+
position: row.position,
|
|
186
|
+
createdAt: row.created_at,
|
|
187
|
+
updatedAt: row.updated_at,
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** How many proposals exist right now, and how old the oldest pending one is. */
|
|
192
|
+
export function proposalSummary(store, { now = new Date() } = {}) {
|
|
193
|
+
const at = now instanceof Date ? now : new Date(now)
|
|
194
|
+
sweepExpired(store, { now: at })
|
|
195
|
+
const counts = store.db.prepare(
|
|
196
|
+
"SELECT status, COUNT(*) AS n FROM block_proposals GROUP BY status",
|
|
197
|
+
).all()
|
|
198
|
+
const byStatus = Object.fromEntries(counts.map((row) => [row.status, row.n]))
|
|
199
|
+
const oldest = store.db.prepare(
|
|
200
|
+
"SELECT MIN(created_at) AS at FROM block_proposals WHERE status = 'pending'",
|
|
201
|
+
).get()?.at
|
|
202
|
+
return {
|
|
203
|
+
pending: byStatus.pending ?? 0,
|
|
204
|
+
stale: byStatus.stale ?? 0,
|
|
205
|
+
applied: byStatus.applied ?? 0,
|
|
206
|
+
oldestAgeMs: oldest ? Math.max(0, at.getTime() - Date.parse(oldest)) : null,
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Expire pending proposals past their deadline. Cheap, idempotent, no timer. */
|
|
211
|
+
export function sweepExpired(store, { now = new Date() } = {}) {
|
|
212
|
+
const at = now instanceof Date ? now : new Date(now)
|
|
213
|
+
const out = store.db.prepare(
|
|
214
|
+
"UPDATE block_proposals SET status = 'expired', updated_at = ? WHERE status = 'pending' AND expires_at <= ?",
|
|
215
|
+
).run(at.toISOString(), at.toISOString())
|
|
216
|
+
return out.changes ?? 0
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Queue one proposal.
|
|
221
|
+
*
|
|
222
|
+
* Order matters: shape validation, then "does this make sense against the current
|
|
223
|
+
* block", then dedupe, then limits. Validating first means the limit counters only
|
|
224
|
+
* ever count requests that could have been accepted.
|
|
225
|
+
*/
|
|
226
|
+
export function propose(store, input, { now = new Date() } = {}) {
|
|
227
|
+
if (!store) throw new Error('propose needs a store')
|
|
228
|
+
const at = now instanceof Date ? now : new Date(now)
|
|
229
|
+
const iso = at.toISOString()
|
|
230
|
+
|
|
231
|
+
const valid = validateProposal(input)
|
|
232
|
+
if (!valid.ok) return { ok: false, status: 400, error: valid.error }
|
|
233
|
+
|
|
234
|
+
const current = store.getBlock({ scopeType: valid.scopeType, scopeId: valid.scopeId, label: valid.label }) ?? null
|
|
235
|
+
if (valid.changeKind === 'create' && current) {
|
|
236
|
+
return { ok: false, status: 409, error: `block ${valid.scopeType}/${valid.scopeId}/${valid.label} already exists; propose a rewrite instead` }
|
|
237
|
+
}
|
|
238
|
+
if (valid.changeKind !== 'create' && !current) {
|
|
239
|
+
return { ok: false, status: 404, error: `block ${valid.scopeType}/${valid.scopeId}/${valid.label} does not exist; propose a create instead` }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// A proposal that would change nothing is noise. The threshold is the same
|
|
243
|
+
// similarity used by the fact decider, so "same but reworded" is caught too.
|
|
244
|
+
if (valid.changeKind === 'rewrite' && current && similarity(current.value, valid.value) >= PROPOSAL_LIMITS.noOpSimilarity) {
|
|
245
|
+
return { ok: false, status: 409, error: 'the proposed value is effectively identical to the current one' }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const dedupeKey = proposalDedupeKey(valid)
|
|
249
|
+
const existing = store.db.prepare(
|
|
250
|
+
"SELECT * FROM block_proposals WHERE dedupe_key = ? AND status IN ('pending','stale','approved')",
|
|
251
|
+
).get(dedupeKey)
|
|
252
|
+
if (existing) {
|
|
253
|
+
// Merge instead of queueing a second copy: the evidence is what makes a
|
|
254
|
+
// proposal convincing, so more of it is welcome, more rows are not.
|
|
255
|
+
const evidence = safeJson(existing.evidence, [])
|
|
256
|
+
const merged = [...evidence, ...valid.evidence].slice(0, 5)
|
|
257
|
+
store.db.prepare(
|
|
258
|
+
'UPDATE block_proposals SET evidence = ?, confidence = ?, updated_at = ? WHERE id = ?',
|
|
259
|
+
).run(JSON.stringify(merged), Math.max(existing.confidence, valid.confidence), iso, existing.id)
|
|
260
|
+
return { ok: true, merged: true, id: existing.id, status: existing.status, proposal: rowToProposal(store.db.prepare('SELECT * FROM block_proposals WHERE id = ?').get(existing.id)) }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const dayAgo = new Date(at.getTime() - DAY_MS).toISOString()
|
|
264
|
+
const rejectSince = new Date(at.getTime() - PROPOSAL_LIMITS.rejectWindowDays * DAY_MS).toISOString()
|
|
265
|
+
|
|
266
|
+
const rejected = store.db.prepare(
|
|
267
|
+
"SELECT COUNT(*) AS n FROM block_proposals WHERE scope_type = ? AND scope_id = ? AND label = ? AND status = 'rejected' AND decided_by LIKE 'human:%' AND updated_at >= ?",
|
|
268
|
+
).get(valid.scopeType, valid.scopeId, valid.label, rejectSince)?.n ?? 0
|
|
269
|
+
if (rejected >= PROPOSAL_LIMITS.rejectionsToCool) {
|
|
270
|
+
const cooledUntil = new Date(at.getTime() + PROPOSAL_LIMITS.rejectCooldownDays * DAY_MS).toISOString()
|
|
271
|
+
return {
|
|
272
|
+
ok: false,
|
|
273
|
+
status: 429,
|
|
274
|
+
error: `this block was rejected ${rejected} times in the last ${PROPOSAL_LIMITS.rejectWindowDays} days; cooling down until ${cooledUntil}`,
|
|
275
|
+
// Returned so a caller can decide rather than guess.
|
|
276
|
+
cooledUntil,
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const pendingForBlock = store.db.prepare(
|
|
281
|
+
"SELECT COUNT(*) AS n FROM block_proposals WHERE scope_type = ? AND scope_id = ? AND label = ? AND status IN ('pending','approved')",
|
|
282
|
+
).get(valid.scopeType, valid.scopeId, valid.label)?.n ?? 0
|
|
283
|
+
if (pendingForBlock >= PROPOSAL_LIMITS.perBlockPending) {
|
|
284
|
+
return { ok: false, status: 429, error: `this block already has ${pendingForBlock} pending proposals; decide those first` }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const perBlockDay = store.db.prepare(
|
|
288
|
+
'SELECT COUNT(*) AS n FROM block_proposals WHERE scope_type = ? AND scope_id = ? AND label = ? AND created_at >= ?',
|
|
289
|
+
).get(valid.scopeType, valid.scopeId, valid.label, dayAgo)?.n ?? 0
|
|
290
|
+
if (perBlockDay >= PROPOSAL_LIMITS.perBlockPerDay) {
|
|
291
|
+
return { ok: false, status: 429, error: `this block has had ${perBlockDay} proposals in 24h; the daily limit is ${PROPOSAL_LIMITS.perBlockPerDay}` }
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const globalDay = store.db.prepare(
|
|
295
|
+
'SELECT COUNT(*) AS n FROM block_proposals WHERE created_at >= ?',
|
|
296
|
+
).get(dayAgo)?.n ?? 0
|
|
297
|
+
if (globalDay >= PROPOSAL_LIMITS.globalPerDay) {
|
|
298
|
+
return { ok: false, status: 429, error: `there have been ${globalDay} proposals in 24h; the limit is ${PROPOSAL_LIMITS.globalPerDay}` }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const id = `prop_${createHash('sha1').update(`${dedupeKey}${iso}`).digest('hex').slice(0, 12)}`
|
|
302
|
+
const expiresAt = new Date(at.getTime() + PROPOSAL_LIMITS.pendingTtlDays * DAY_MS).toISOString()
|
|
303
|
+
store.db.prepare(`
|
|
304
|
+
INSERT INTO block_proposals
|
|
305
|
+
(id, scope_type, scope_id, label, change_kind, base_value, base_updated_at, base_row,
|
|
306
|
+
proposed_value, evidence, confidence, proposer, status, dedupe_key,
|
|
307
|
+
created_at, updated_at, expires_at)
|
|
308
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'pending',?,?,?,?)
|
|
309
|
+
`).run(
|
|
310
|
+
id, valid.scopeType, valid.scopeId, valid.label, valid.changeKind,
|
|
311
|
+
current ? current.value : null,
|
|
312
|
+
current ? current.updated_at : null,
|
|
313
|
+
current ? JSON.stringify(blockRowToSnapshot(current)) : null,
|
|
314
|
+
valid.value,
|
|
315
|
+
JSON.stringify(valid.evidence),
|
|
316
|
+
valid.confidence,
|
|
317
|
+
valid.proposer,
|
|
318
|
+
dedupeKey, iso, iso, expiresAt,
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
return {
|
|
322
|
+
ok: true,
|
|
323
|
+
merged: false,
|
|
324
|
+
id,
|
|
325
|
+
status: 'pending',
|
|
326
|
+
proposal: rowToProposal(store.db.prepare('SELECT * FROM block_proposals WHERE id = ?').get(id)),
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* List proposals, newest first, with the counts the panel needs beside them.
|
|
332
|
+
*
|
|
333
|
+
* `pending` is swept first so a caller never sees a queue that should have closed.
|
|
334
|
+
*/
|
|
335
|
+
export function listProposals(store, { status = 'pending', limit = 20, now = new Date() } = {}) {
|
|
336
|
+
if (!store) throw new Error('listProposals needs a store')
|
|
337
|
+
const at = now instanceof Date ? now : new Date(now)
|
|
338
|
+
sweepExpired(store, { now: at })
|
|
339
|
+
const where = status === 'all' || !status ? '' : 'WHERE status = ?'
|
|
340
|
+
const params = where ? [status] : []
|
|
341
|
+
const rows = store.db.prepare(
|
|
342
|
+
`SELECT * FROM block_proposals ${where} ORDER BY created_at DESC LIMIT ?`,
|
|
343
|
+
).all(...params, Math.min(Math.max(Number(limit) || 20, 1), 100))
|
|
344
|
+
return {
|
|
345
|
+
items: rows.map(rowToProposal),
|
|
346
|
+
summary: proposalSummary(store, { now: at }),
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** All proposals aimed at one block, for the "is something else queued?" check. */
|
|
351
|
+
function competingForBlock(store, proposal) {
|
|
352
|
+
return store.db.prepare(
|
|
353
|
+
"SELECT * FROM block_proposals WHERE scope_type = ? AND scope_id = ? AND label = ? AND status IN ('pending','approved') AND id <> ?",
|
|
354
|
+
).all(proposal.scope_type, proposal.scope_id, proposal.label, proposal.id)
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Apply, refuse or undo one proposal.
|
|
359
|
+
*
|
|
360
|
+
* Approval re-reads the block inside the transaction: a proposal is diffed against
|
|
361
|
+
* the value it was drafted from, and applying it over a human's newer edit would
|
|
362
|
+
* silently undo that edit. Drift is a 409 and the proposal goes `stale`, never a
|
|
363
|
+
* best-effort merge — this is the one race in the design that must fail closed.
|
|
364
|
+
*/
|
|
365
|
+
export function decideProposal(store, input = {}, { now = new Date(), commit = commitBlock } = {}) {
|
|
366
|
+
if (!store) throw new Error('decideProposal needs a store')
|
|
367
|
+
const at = now instanceof Date ? now : new Date(now)
|
|
368
|
+
const iso = at.toISOString()
|
|
369
|
+
|
|
370
|
+
const action = String(input?.action ?? '').trim()
|
|
371
|
+
if (!PROPOSAL_ACTIONS.includes(action)) {
|
|
372
|
+
return { ok: false, status: 400, error: `action must be one of ${PROPOSAL_ACTIONS.join(' | ')}` }
|
|
373
|
+
}
|
|
374
|
+
const id = String(input?.id ?? '').trim()
|
|
375
|
+
if (!id) return { ok: false, status: 400, error: 'id is required' }
|
|
376
|
+
const note = String(input?.note ?? '').trim()
|
|
377
|
+
|
|
378
|
+
const row = store.db.prepare('SELECT * FROM block_proposals WHERE id = ?').get(id)
|
|
379
|
+
if (!row) return { ok: false, status: 404, error: `no proposal ${id}` }
|
|
380
|
+
const proposal = rowToProposal(row)
|
|
381
|
+
|
|
382
|
+
if (action === 'approve') {
|
|
383
|
+
if (proposal.status === 'stale') {
|
|
384
|
+
return { ok: false, status: 409, error: 'this proposal went stale: the block changed after it was drafted' }
|
|
385
|
+
}
|
|
386
|
+
if (proposal.status !== 'pending' && proposal.status !== 'approved') {
|
|
387
|
+
return { ok: false, status: 409, error: `cannot approve a proposal in status ${proposal.status}` }
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
return store.transaction(() => {
|
|
391
|
+
const current = store.getBlock({ scopeType: proposal.scopeType, scopeId: proposal.scopeId, label: proposal.label }) ?? null
|
|
392
|
+
const drifted = proposal.changeKind === 'create'
|
|
393
|
+
? Boolean(current)
|
|
394
|
+
: !current || current.updated_at !== proposal.baseUpdatedAt
|
|
395
|
+
if (drifted) {
|
|
396
|
+
store.db.prepare("UPDATE block_proposals SET status = 'stale', updated_at = ? WHERE id = ?").run(iso, id)
|
|
397
|
+
return {
|
|
398
|
+
ok: false,
|
|
399
|
+
status: 409,
|
|
400
|
+
error: 'the block changed after this proposal was drafted; ask for a fresh proposal or rebase',
|
|
401
|
+
currentUpdatedAt: current?.updated_at ?? null,
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const committed = commit({
|
|
406
|
+
store,
|
|
407
|
+
scopeType: proposal.scopeType,
|
|
408
|
+
scopeId: proposal.scopeId,
|
|
409
|
+
label: proposal.label,
|
|
410
|
+
action: proposal.changeKind === 'delete' ? 'delete' : 'set',
|
|
411
|
+
value: proposal.proposedValue,
|
|
412
|
+
valueLimit: current?.value_limit ?? 2000,
|
|
413
|
+
position: current?.position ?? 0,
|
|
414
|
+
actor: 'human:approve',
|
|
415
|
+
proposalId: id,
|
|
416
|
+
at: iso,
|
|
417
|
+
})
|
|
418
|
+
|
|
419
|
+
store.db.prepare(
|
|
420
|
+
"UPDATE block_proposals SET status = 'applied', applied_at = ?, applied_value = ?, decided_by = 'human:panel', decided_at = ?, updated_at = ? WHERE id = ?",
|
|
421
|
+
).run(iso, proposal.changeKind === 'delete' ? '' : proposal.proposedValue, iso, iso, id)
|
|
422
|
+
|
|
423
|
+
// Two proposals for the same block cannot both be true. The loser is marked
|
|
424
|
+
// rejected-by-system rather than deleted: a person who saw both options
|
|
425
|
+
// should still be able to see which one won and which one lost.
|
|
426
|
+
const losers = competingForBlock(store, row)
|
|
427
|
+
for (const loser of losers) {
|
|
428
|
+
store.db.prepare(
|
|
429
|
+
"UPDATE block_proposals SET status = 'rejected', decided_by = 'system:superseded', decided_at = ?, decision_note = ?, updated_at = ? WHERE id = ?",
|
|
430
|
+
).run(iso, `superseded by ${id}`, iso, loser.id)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
return {
|
|
434
|
+
ok: true,
|
|
435
|
+
status: 200,
|
|
436
|
+
proposal: rowToProposal(store.db.prepare('SELECT * FROM block_proposals WHERE id = ?').get(id)),
|
|
437
|
+
row: committed.row ?? null,
|
|
438
|
+
superseded: losers.map((loser) => loser.id),
|
|
439
|
+
}
|
|
440
|
+
})
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (action === 'reject') {
|
|
444
|
+
if (proposal.status !== 'pending' && proposal.status !== 'stale') {
|
|
445
|
+
return { ok: false, status: 409, error: `cannot reject a proposal in status ${proposal.status}` }
|
|
446
|
+
}
|
|
447
|
+
// A rejection without a reason is unusable: it is the only input the cooldown
|
|
448
|
+
// and the next reviewer have about why this idea was wrong.
|
|
449
|
+
if (!note) return { ok: false, status: 400, error: 'a rejection needs a note saying why' }
|
|
450
|
+
store.db.prepare(
|
|
451
|
+
"UPDATE block_proposals SET status = 'rejected', decided_by = 'human:panel', decided_at = ?, decision_note = ?, updated_at = ? WHERE id = ?",
|
|
452
|
+
).run(iso, note, iso, id)
|
|
453
|
+
return { ok: true, status: 200, proposal: rowToProposal(store.db.prepare('SELECT * FROM block_proposals WHERE id = ?').get(id)) }
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// rollback
|
|
457
|
+
if (proposal.status !== 'applied') {
|
|
458
|
+
return { ok: false, status: 409, error: `cannot roll back a proposal in status ${proposal.status}` }
|
|
459
|
+
}
|
|
460
|
+
const current = store.getBlock({ scopeType: proposal.scopeType, scopeId: proposal.scopeId, label: proposal.label }) ?? null
|
|
461
|
+
const currentValue = current?.value ?? ''
|
|
462
|
+
if (currentValue !== proposal.appliedValue) {
|
|
463
|
+
if (input?.force !== true) {
|
|
464
|
+
return { ok: false, status: 409, error: 'the block was edited after this proposal was applied; pass force with a note to restore the earlier value anyway' }
|
|
465
|
+
}
|
|
466
|
+
if (!note) return { ok: false, status: 400, error: 'a forced rollback needs a note' }
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const base = safeJson(row.base_row, null)
|
|
470
|
+
return store.transaction(() => {
|
|
471
|
+
if (proposal.changeKind === 'create' || !base) {
|
|
472
|
+
commit({
|
|
473
|
+
store,
|
|
474
|
+
scopeType: proposal.scopeType,
|
|
475
|
+
scopeId: proposal.scopeId,
|
|
476
|
+
label: proposal.label,
|
|
477
|
+
action: 'delete',
|
|
478
|
+
actor: 'human:rollback',
|
|
479
|
+
historyAction: 'rollback',
|
|
480
|
+
proposalId: id,
|
|
481
|
+
at: iso,
|
|
482
|
+
})
|
|
483
|
+
} else {
|
|
484
|
+
commit({
|
|
485
|
+
store,
|
|
486
|
+
scopeType: proposal.scopeType,
|
|
487
|
+
scopeId: proposal.scopeId,
|
|
488
|
+
label: proposal.label,
|
|
489
|
+
action: 'set',
|
|
490
|
+
value: base.value ?? '',
|
|
491
|
+
valueLimit: base.valueLimit ?? 2000,
|
|
492
|
+
position: base.position ?? 0,
|
|
493
|
+
actor: 'human:rollback',
|
|
494
|
+
historyAction: 'rollback',
|
|
495
|
+
proposalId: id,
|
|
496
|
+
at: iso,
|
|
497
|
+
})
|
|
498
|
+
}
|
|
499
|
+
store.db.prepare(
|
|
500
|
+
"UPDATE block_proposals SET status = 'rolled_back', rolled_back_at = ?, updated_at = ? WHERE id = ?",
|
|
501
|
+
).run(iso, iso, id)
|
|
502
|
+
return {
|
|
503
|
+
ok: true,
|
|
504
|
+
status: 200,
|
|
505
|
+
proposal: rowToProposal(store.db.prepare('SELECT * FROM block_proposals WHERE id = ?').get(id)),
|
|
506
|
+
}
|
|
507
|
+
})
|
|
508
|
+
}
|
package/lib/core/schema.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* version to read rather than a schema to guess.
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
export const SCHEMA_VERSION =
|
|
15
|
+
export const SCHEMA_VERSION = 3
|
|
16
16
|
|
|
17
17
|
export const DDL = `
|
|
18
18
|
PRAGMA journal_mode = WAL;
|
|
@@ -120,4 +120,162 @@ CREATE TABLE IF NOT EXISTS flags (
|
|
|
120
120
|
created_at TEXT NOT NULL,
|
|
121
121
|
PRIMARY KEY (memory_id, reason)
|
|
122
122
|
) WITHOUT ROWID;
|
|
123
|
+
|
|
124
|
+
-- ── v2: the evolution planes ────────────────────────────────────────────────
|
|
125
|
+
--
|
|
126
|
+
-- Everything below is additive. The v1 tables are untouched on purpose: their
|
|
127
|
+
-- CHECK constraints carry meaning (memory_type is exactly three values,
|
|
128
|
+
-- history.action exactly five) and SQLite cannot alter a CHECK, so a new enum
|
|
129
|
+
-- means a new table rather than a rebuilt one.
|
|
130
|
+
--
|
|
131
|
+
-- The blocks table keeps being the CURRENT value with no version column. Its
|
|
132
|
+
-- history lives in blocks_history, written by one function, because a block
|
|
133
|
+
-- change without a recorded before-image cannot be reviewed or rolled back.
|
|
134
|
+
|
|
135
|
+
CREATE TABLE IF NOT EXISTS block_proposals (
|
|
136
|
+
id TEXT PRIMARY KEY,
|
|
137
|
+
scope_type TEXT NOT NULL CHECK (scope_type IN ('user','agent')),
|
|
138
|
+
scope_id TEXT NOT NULL,
|
|
139
|
+
label TEXT NOT NULL,
|
|
140
|
+
change_kind TEXT NOT NULL CHECK (change_kind IN ('create','rewrite','delete','merge')),
|
|
141
|
+
base_value TEXT,
|
|
142
|
+
base_updated_at TEXT,
|
|
143
|
+
base_row TEXT,
|
|
144
|
+
proposed_value TEXT NOT NULL DEFAULT '',
|
|
145
|
+
merge_from TEXT,
|
|
146
|
+
evidence TEXT NOT NULL DEFAULT '[]',
|
|
147
|
+
confidence REAL NOT NULL DEFAULT 0,
|
|
148
|
+
proposer TEXT NOT NULL CHECK (proposer IN ('extract','manual','panel')),
|
|
149
|
+
status TEXT NOT NULL DEFAULT 'pending'
|
|
150
|
+
CHECK (status IN ('pending','stale','approved','applied',
|
|
151
|
+
'rolled_back','rejected','expired')),
|
|
152
|
+
dedupe_key TEXT NOT NULL,
|
|
153
|
+
created_at TEXT NOT NULL,
|
|
154
|
+
updated_at TEXT NOT NULL,
|
|
155
|
+
expires_at TEXT NOT NULL,
|
|
156
|
+
decided_by TEXT,
|
|
157
|
+
decided_at TEXT,
|
|
158
|
+
decision_note TEXT,
|
|
159
|
+
applied_at TEXT,
|
|
160
|
+
applied_value TEXT,
|
|
161
|
+
rolled_back_at TEXT
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
CREATE UNIQUE INDEX IF NOT EXISTS proposals_active_dedupe
|
|
165
|
+
ON block_proposals(dedupe_key) WHERE status IN ('pending','stale','approved');
|
|
166
|
+
CREATE INDEX IF NOT EXISTS proposals_queue ON block_proposals(status, expires_at);
|
|
167
|
+
CREATE INDEX IF NOT EXISTS proposals_target
|
|
168
|
+
ON block_proposals(scope_type, scope_id, label, status);
|
|
169
|
+
|
|
170
|
+
CREATE TABLE IF NOT EXISTS blocks_history (
|
|
171
|
+
id INTEGER PRIMARY KEY,
|
|
172
|
+
scope_type TEXT NOT NULL,
|
|
173
|
+
scope_id TEXT NOT NULL,
|
|
174
|
+
label TEXT NOT NULL,
|
|
175
|
+
action TEXT NOT NULL CHECK (action IN ('set','update','delete','rollback','migrate')),
|
|
176
|
+
row_before TEXT,
|
|
177
|
+
row_after TEXT,
|
|
178
|
+
proposal_id TEXT,
|
|
179
|
+
actor TEXT NOT NULL,
|
|
180
|
+
at TEXT NOT NULL
|
|
181
|
+
);
|
|
182
|
+
CREATE INDEX IF NOT EXISTS blocks_history_block
|
|
183
|
+
ON blocks_history(scope_type, scope_id, label, id);
|
|
184
|
+
|
|
185
|
+
CREATE TABLE IF NOT EXISTS knowledge (
|
|
186
|
+
memory_id TEXT PRIMARY KEY REFERENCES memories(id) ON DELETE CASCADE,
|
|
187
|
+
kind TEXT NOT NULL CHECK (kind IN
|
|
188
|
+
('rationale','contract','failure','dependency','solution','persona')),
|
|
189
|
+
scope_level TEXT NOT NULL DEFAULT 'project'
|
|
190
|
+
CHECK (scope_level IN ('global','domain','project')),
|
|
191
|
+
-- Empty string, not NULL: SQLite treats NULLs as distinct in a UNIQUE index,
|
|
192
|
+
-- so a NULL here would let the same global entry be inserted forever.
|
|
193
|
+
domain TEXT NOT NULL DEFAULT '',
|
|
194
|
+
dedupe_key TEXT NOT NULL,
|
|
195
|
+
confidence REAL NOT NULL DEFAULT 0.5 CHECK (confidence BETWEEN 0 AND 1),
|
|
196
|
+
status TEXT NOT NULL DEFAULT 'proposed'
|
|
197
|
+
CHECK (status IN ('proposed','active','stale','retired')),
|
|
198
|
+
review_after TEXT,
|
|
199
|
+
expires_at TEXT,
|
|
200
|
+
used_count INTEGER NOT NULL DEFAULT 0,
|
|
201
|
+
refuted_count INTEGER NOT NULL DEFAULT 0,
|
|
202
|
+
-- v3: set when a promotion proposal was created for this row (or when it was
|
|
203
|
+
-- already present in the block). Without it the next extraction run would
|
|
204
|
+
-- re-propose the same sentence forever.
|
|
205
|
+
promoted_at TEXT,
|
|
206
|
+
proposal_id TEXT,
|
|
207
|
+
created_at TEXT NOT NULL,
|
|
208
|
+
updated_at TEXT NOT NULL,
|
|
209
|
+
UNIQUE (scope_level, domain, dedupe_key)
|
|
210
|
+
);
|
|
211
|
+
CREATE INDEX IF NOT EXISTS knowledge_kind_status ON knowledge(kind, status);
|
|
212
|
+
CREATE INDEX IF NOT EXISTS knowledge_domain
|
|
213
|
+
ON knowledge(domain, status) WHERE status = 'active';
|
|
214
|
+
CREATE INDEX IF NOT EXISTS knowledge_review
|
|
215
|
+
ON knowledge(review_after) WHERE status IN ('active','stale');
|
|
216
|
+
|
|
217
|
+
CREATE TABLE IF NOT EXISTS knowledge_evidence (
|
|
218
|
+
id INTEGER PRIMARY KEY,
|
|
219
|
+
memory_id TEXT NOT NULL REFERENCES knowledge(memory_id) ON DELETE CASCADE,
|
|
220
|
+
source_kind TEXT NOT NULL CHECK (source_kind IN
|
|
221
|
+
('turn','tool_call','tool_result','diagnostic','panel_flag',
|
|
222
|
+
'retrieval_miss','manual')),
|
|
223
|
+
session_id TEXT NOT NULL DEFAULT '',
|
|
224
|
+
seq INTEGER,
|
|
225
|
+
tool_name TEXT NOT NULL DEFAULT '',
|
|
226
|
+
excerpt TEXT NOT NULL CHECK (length(excerpt) <= 280),
|
|
227
|
+
weight REAL NOT NULL DEFAULT 1.0,
|
|
228
|
+
captured_at TEXT NOT NULL
|
|
229
|
+
);
|
|
230
|
+
CREATE INDEX IF NOT EXISTS knowledge_evidence_memory ON knowledge_evidence(memory_id);
|
|
231
|
+
|
|
232
|
+
-- The flywheel's missing input. Until v2, a search knew whether it answered and
|
|
233
|
+
-- then forgot: nothing recorded that a memory had been retrieved, so the question
|
|
234
|
+
-- of whether a piece of knowledge was ever used had no data behind it, and any
|
|
235
|
+
-- promotion threshold built on used_count would have been decorative.
|
|
236
|
+
CREATE TABLE IF NOT EXISTS retrievals (
|
|
237
|
+
id INTEGER PRIMARY KEY,
|
|
238
|
+
at TEXT NOT NULL,
|
|
239
|
+
query TEXT NOT NULL,
|
|
240
|
+
top_id TEXT,
|
|
241
|
+
hit INTEGER NOT NULL,
|
|
242
|
+
answerable INTEGER,
|
|
243
|
+
channel_kw INTEGER NOT NULL DEFAULT 0,
|
|
244
|
+
channel_vec INTEGER NOT NULL DEFAULT 0,
|
|
245
|
+
injected INTEGER NOT NULL DEFAULT 0
|
|
246
|
+
);
|
|
247
|
+
CREATE INDEX IF NOT EXISTS retrievals_at ON retrievals(at DESC);
|
|
248
|
+
CREATE INDEX IF NOT EXISTS retrievals_top ON retrievals(top_id, at);
|
|
249
|
+
|
|
250
|
+
CREATE TABLE IF NOT EXISTS domains (
|
|
251
|
+
domain_id TEXT PRIMARY KEY,
|
|
252
|
+
name TEXT NOT NULL,
|
|
253
|
+
version INTEGER NOT NULL DEFAULT 1,
|
|
254
|
+
status TEXT NOT NULL DEFAULT 'draft'
|
|
255
|
+
CHECK (status IN ('draft','active','stale','suspended','retired')),
|
|
256
|
+
index_text TEXT NOT NULL CHECK (length(index_text) <= 600),
|
|
257
|
+
detail_text TEXT NOT NULL DEFAULT '',
|
|
258
|
+
signals TEXT NOT NULL DEFAULT '{}',
|
|
259
|
+
gates TEXT NOT NULL DEFAULT '[]',
|
|
260
|
+
redlines TEXT NOT NULL DEFAULT '[]',
|
|
261
|
+
sources TEXT NOT NULL DEFAULT '[]',
|
|
262
|
+
ttl_days INTEGER NOT NULL DEFAULT 90,
|
|
263
|
+
use_count INTEGER NOT NULL DEFAULT 0,
|
|
264
|
+
ok_count INTEGER NOT NULL DEFAULT 0,
|
|
265
|
+
last_used_at TEXT,
|
|
266
|
+
checked_at TEXT,
|
|
267
|
+
approved_by TEXT,
|
|
268
|
+
approved_at TEXT,
|
|
269
|
+
created_at TEXT NOT NULL,
|
|
270
|
+
updated_at TEXT NOT NULL
|
|
271
|
+
) WITHOUT ROWID;
|
|
272
|
+
|
|
273
|
+
CREATE TABLE IF NOT EXISTS domain_events (
|
|
274
|
+
id INTEGER PRIMARY KEY,
|
|
275
|
+
domain_id TEXT NOT NULL,
|
|
276
|
+
kind TEXT NOT NULL,
|
|
277
|
+
detail TEXT NOT NULL DEFAULT '{}',
|
|
278
|
+
at TEXT NOT NULL
|
|
279
|
+
);
|
|
280
|
+
CREATE INDEX IF NOT EXISTS domain_events_by_domain ON domain_events(domain_id, at);
|
|
123
281
|
`
|