dsh-memvault 0.10.0 → 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/lib/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  window.__ModuleLoader__.load({ id: "dsh-memvault", factory: (require) => { var module = { exports: {} }; var exports = module.exports;
2
2
  // generated from src/client/index.js by scripts/build-client.mjs — do not edit
3
- // source-sha256: 9e5dd40c233914b7
3
+ // source-sha256: 2cd042854c3930a6
4
4
  /**
5
5
  * dsh-memvault — browser half: the memory panel.
6
6
  *
@@ -36,6 +36,9 @@ const FLAG_URL = '/memvault/api/flag'
36
36
  const REINDEX_URL = '/memvault/api/reindex'
37
37
  const REVIEW_URL = '/memvault/api/review'
38
38
  const REPLAY_URL = '/memvault/api/replay'
39
+ const PROPOSALS_URL = '/memvault/api/proposals'
40
+ const DOMAIN_URL = '/memvault/api/domain'
41
+ const KNOWLEDGE_URL = '/memvault/api/knowledge'
39
42
  const POLL_MS = 15000
40
43
 
41
44
  const C = {
@@ -153,6 +156,7 @@ function Details({ summary, children }) {
153
156
 
154
157
  /** Vector backfill: the only write that costs embedding calls, so it is explicit. */
155
158
  function VectorCard({ url }) {
159
+ const [knowledge, setKnowledge] = useState(null)
156
160
  const [busy, setBusy] = useState(false)
157
161
  const [line, setLine] = useState('')
158
162
  const call = async (apply) => {
@@ -381,6 +385,7 @@ function ReviewCard({ refreshToken, onChanged, onError }) {
381
385
  const [editing, setEditing] = useState(null)
382
386
  const [draft, setDraft] = useState('')
383
387
  const [extractor, setExtractor] = useState('inherit')
388
+ const [knowledge, setKnowledge] = useState(null)
384
389
  const [busy, setBusy] = useState(false)
385
390
 
386
391
  const load = () => {
@@ -999,10 +1004,18 @@ function StructureView({ onError }) {
999
1004
  ),
1000
1005
  ),
1001
1006
 
1007
+ // Folding: only scopes that are injected, or that hold real volume, stay
1008
+ // expanded. A scope with no injected block and almost no memories is history,
1009
+ // not structure — four of them used to render as four full cards.
1002
1010
  h('div', { style: S.grid },
1003
- (data.dimensions ?? []).filter((dim) => dim.values.length > 0).map((dim) =>
1004
- h(Card, { key: dim.key, title: `${dim.key} 维度(${dim.values.length})` },
1005
- dim.values.slice(0, 8).map((value) => h('div', { key: value.id, style: S.block },
1011
+ (data.dimensions ?? []).filter((dim) => dim.values.length > 0).map((dim) => {
1012
+ const isMain = (value) => value.memories >= 10 || value.blocks.some((block) => block.injected)
1013
+ const shown = dim.values.filter(isMain).slice(0, 8)
1014
+ const folded = dim.values.filter((value) => !isMain(value))
1015
+ const foldedMemories = folded.reduce((sum, value) => sum + value.memories, 0)
1016
+ const foldedBlocks = folded.reduce((sum, value) => sum + value.blocks.length, 0)
1017
+ return h(Card, { key: dim.key, title: `${dim.key} 维度(${dim.values.length})` },
1018
+ shown.map((value) => h('div', { key: value.id, style: S.block },
1006
1019
  h('div', { style: S.blockHead },
1007
1020
  h('span', { style: S.badge(C.idle) }, dim.key),
1008
1021
  h('span', { style: S.mono }, value.id),
@@ -1030,8 +1043,14 @@ function StructureView({ onError }) {
1030
1043
  )),
1031
1044
  ),
1032
1045
  )),
1033
- ),
1034
- ),
1046
+ folded.length > 0 && h(Details, {
1047
+ summary: `其他 ${folded.length} 个未注入/零散作用域(记忆 ${foldedMemories} · 块 ${foldedBlocks})`,
1048
+ },
1049
+ folded.map((value) => h('div', { key: value.id, style: S.grid },
1050
+ h(KV, { k: value.id, v: `记忆 ${value.memories} · 块 ${value.blocks.length}` }))),
1051
+ ),
1052
+ )
1053
+ }),
1035
1054
  ),
1036
1055
 
1037
1056
  h(Card, { title: `关系图(${graph.nodes.length} 个节点 / ${graph.edges.length} 条边)` },
@@ -1152,6 +1171,7 @@ function MemoriesView({ onError, initialIds = '' }) {
1152
1171
  const [ids, setIds] = useState(initialIds)
1153
1172
  const [onlyFlagged, setOnlyFlagged] = useState(false)
1154
1173
  const [onlyRetyped, setOnlyRetyped] = useState(false)
1174
+ const [knowledge, setKnowledge] = useState(null)
1155
1175
  const [busy, setBusy] = useState(false)
1156
1176
  const [reviewToken, setReviewToken] = useState(0)
1157
1177
  const [query, setQuery] = useState({ q: '', type: '', limit: 20, offset: 0 })
@@ -1296,8 +1316,585 @@ function MemoriesView({ onError, initialIds = '' }) {
1296
1316
  )
1297
1317
  }
1298
1318
 
1319
+ const PROPOSAL_TONE = {
1320
+ pending: C.brand,
1321
+ stale: C.warn,
1322
+ approved: C.brand,
1323
+ applied: C.ok,
1324
+ rejected: C.err,
1325
+ rolled_back: C.warn,
1326
+ expired: C.idle,
1327
+ }
1328
+
1329
+ /** One proposal: what it would change, why, and the only two buttons that matter. */
1330
+ function ProposalRow({ item, writable, busy, onDecide }) {
1331
+ const tone = PROPOSAL_TONE[item.status] ?? C.muted
1332
+ const open = item.status === 'pending' || item.status === 'stale'
1333
+ const evidence = Array.isArray(item.evidence) ? item.evidence : []
1334
+ return h('div', { style: { ...S.card, marginBottom: '8px' } },
1335
+ h('div', { style: S.toolHead },
1336
+ h('span', { style: S.v }, `${item.scopeType}/${item.scopeId}/${item.label}`),
1337
+ h('span', { style: S.small(tone) }, item.status),
1338
+ h('span', { style: S.toolMeta }, `${item.changeKind} · ${item.proposer} · 置信 ${Math.round((item.confidence ?? 0) * 100)}%`),
1339
+ h('span', { style: S.toolMeta }, `${fmtAge(Date.now() - Date.parse(item.createdAt))}前`),
1340
+ ),
1341
+ item.changeKind === 'delete'
1342
+ ? h('div', { style: S.toolText }, '删除该块')
1343
+ : h('div', null,
1344
+ item.baseValue !== null && item.baseValue !== undefined && h('div', { style: S.toolRaw }, `− ${item.baseValue}`),
1345
+ h('div', { style: S.toolRaw }, `+ ${item.proposedValue}`),
1346
+ ),
1347
+ evidence.length > 0 && h('div', { style: S.toolMeta },
1348
+ `证据:${evidence.map((e) => e.quote ?? '').filter(Boolean).slice(0, 3).join(' / ')}`),
1349
+ item.decisionNote && h('div', { style: S.toolMeta }, `理由:${item.decisionNote}`),
1350
+ h('div', { style: { ...S.rowActions, marginTop: '6px' } },
1351
+ open && h('button', {
1352
+ style: S.small(writable ? C.ok : C.muted),
1353
+ disabled: !writable || busy,
1354
+ title: writable ? '写入核心块' : '面板只读(config panel.writes: false)',
1355
+ onClick: () => onDecide(item.id, 'approve'),
1356
+ }, '批准'),
1357
+ open && h('button', {
1358
+ style: S.small(C.err),
1359
+ disabled: !writable || busy,
1360
+ onClick: () => onDecide(item.id, 'reject'),
1361
+ }, '拒绝'),
1362
+ item.status === 'applied' && h('button', {
1363
+ style: S.small(C.warn),
1364
+ disabled: !writable || busy,
1365
+ onClick: () => onDecide(item.id, 'rollback'),
1366
+ }, '回滚'),
1367
+ ),
1368
+ )
1369
+ }
1370
+
1371
+ const DOMAIN_STATUS_TONE = {
1372
+ active: C.ok,
1373
+ draft: C.idle,
1374
+ stale: C.warn,
1375
+ suspended: C.muted,
1376
+ retired: C.muted,
1377
+ }
1378
+
1379
+ /** One pack: what it is, whether it is injected now, and the one decision left. */
1380
+ function DomainRow({ pack, injected, writable, busy, onStatus }) {
1381
+ const tone = DOMAIN_STATUS_TONE[pack.status] ?? C.muted
1382
+ const approve = pack.status === 'draft' || pack.status === 'stale' || pack.status === 'suspended'
1383
+ return h('div', { style: { ...S.card, marginBottom: '8px' } },
1384
+ h('div', { style: S.toolHead },
1385
+ h('span', { style: S.v }, pack.domainId),
1386
+ h('span', { style: S.toolMeta }, pack.name),
1387
+ h('span', { style: S.small(tone) }, pack.status),
1388
+ injected && h('span', { style: S.small(C.brand) }, '已注入'),
1389
+ pack.useCount > 0 && h('span', { style: S.toolMeta }, `用过 ${pack.useCount} 次`),
1390
+ ),
1391
+ h('div', { style: S.toolRaw }, pack.indexText),
1392
+ h('div', { style: S.toolMeta },
1393
+ `触发词:${(pack.signals?.keywords ?? []).slice(0, 6).join('、') || '—'}`
1394
+ + ` 标记:${(pack.signals?.fileMarkers ?? []).slice(0, 4).join('、') || '—'}`
1395
+ + ` 来源:${(pack.sources ?? []).length}`),
1396
+ h('div', { style: { ...S.rowActions, marginTop: '6px' } },
1397
+ approve && h('button', {
1398
+ style: S.small(writable ? C.ok : C.muted),
1399
+ disabled: !writable || busy,
1400
+ title: writable ? '批准后才会被注入' : '面板只读',
1401
+ onClick: () => onStatus(pack.domainId, 'active'),
1402
+ }, pack.status === 'draft' ? '批准' : '恢复'),
1403
+ (pack.status === 'active') && h('button', {
1404
+ style: S.small(C.muted),
1405
+ disabled: !writable || busy,
1406
+ onClick: () => onStatus(pack.domainId, 'suspended'),
1407
+ }, '停用'),
1408
+ ),
1409
+ )
1410
+ }
1411
+
1412
+ /**
1413
+ * The evolution tab: core-block proposals waiting for a human, and the domain
1414
+ * packs that decide what background the model gets.
1415
+ *
1416
+ * Both are "a human deciding what enters the prompt", which is why they share a
1417
+ * tab: the same reviewer should see a proposed rule and the vertical it belongs to.
1418
+ */
1419
+ function ProposalsView({ writable, onError }) {
1420
+ const [items, setItems] = useState([])
1421
+ const [summary, setSummary] = useState(null)
1422
+ const [unavailable, setUnavailable] = useState(false)
1423
+ const [domains, setDomains] = useState([])
1424
+ const [injectedDomains, setInjectedDomains] = useState([])
1425
+ const [knowledge, setKnowledge] = useState(null)
1426
+ const [busy, setBusy] = useState(false)
1427
+ const [error, setError] = useState(null)
1428
+ const [tick, setTick] = useState(0)
1429
+
1430
+ useEffect(() => {
1431
+ let alive = true
1432
+ ;(async () => {
1433
+ try {
1434
+ const [proposalRes, domainRes, knowledgeRes] = await Promise.all([
1435
+ fetch(`${PROPOSALS_URL}?status=all&limit=50`),
1436
+ fetch(DOMAIN_URL),
1437
+ fetch(KNOWLEDGE_URL),
1438
+ ])
1439
+ const json = await proposalRes.json().catch(() => null)
1440
+ if (!proposalRes.ok || json?.ok !== true) throw new Error(`HTTP ${proposalRes.status}${json?.error ? ` · ${json.error}` : ''}`)
1441
+ const domainJson = await domainRes.json().catch(() => null)
1442
+ const knowledgeJson = await knowledgeRes.json().catch(() => null)
1443
+ if (!alive) return
1444
+ setItems(Array.isArray(json.items) ? json.items : [])
1445
+ setSummary(json.summary ?? null)
1446
+ setUnavailable(json.unavailable === true)
1447
+ if (domainJson?.ok === true) {
1448
+ setDomains(Array.isArray(domainJson.domains) ? domainJson.domains : [])
1449
+ setInjectedDomains(Array.isArray(domainJson.active) ? domainJson.active : [])
1450
+ }
1451
+ if (knowledgeJson?.ok === true) setKnowledge(knowledgeJson)
1452
+ setError(null)
1453
+ } catch (err) {
1454
+ if (alive) setError(String(err?.message ?? err))
1455
+ }
1456
+ })()
1457
+ return () => { alive = false }
1458
+ }, [tick])
1459
+
1460
+ /** Change a pack's status. Only a human can approve; the route enforces it too. */
1461
+ const setDomainStatus = async (domainId, status) => {
1462
+ setBusy(true)
1463
+ try {
1464
+ const res = await fetch(DOMAIN_URL, {
1465
+ method: 'POST',
1466
+ headers: { 'content-type': 'application/json' },
1467
+ body: JSON.stringify({ action: 'status', domain_id: domainId, status }),
1468
+ })
1469
+ const json = await res.json().catch(() => null)
1470
+ if (!res.ok || json?.ok !== true) {
1471
+ setError(`HTTP ${res.status}${json?.error ? ` · ${json.error}` : ''}`)
1472
+ return
1473
+ }
1474
+ setError(null)
1475
+ setTick((n) => n + 1)
1476
+ } catch (err) {
1477
+ setError(String(err?.message ?? err))
1478
+ onError?.(String(err?.message ?? err))
1479
+ } finally {
1480
+ setBusy(false)
1481
+ }
1482
+ }
1483
+
1484
+ const decide = async (id, action) => {
1485
+ let note = ''
1486
+ if (action === 'reject') {
1487
+ const answer = window.prompt('拒绝理由(必填,会进冷却统计)', '')
1488
+ if (answer === null) return
1489
+ note = answer
1490
+ } else if (action === 'rollback') {
1491
+ const answer = window.prompt('回滚说明(块在这次批准后被改过时必填)', '')
1492
+ if (answer === null) return
1493
+ note = answer
1494
+ }
1495
+ setBusy(true)
1496
+ try {
1497
+ const res = await fetch(PROPOSALS_URL, {
1498
+ method: 'POST',
1499
+ headers: { 'content-type': 'application/json' },
1500
+ body: JSON.stringify({ id, action, note, force: action === 'rollback' && note !== '' }),
1501
+ })
1502
+ const json = await res.json().catch(() => null)
1503
+ if (!res.ok || json?.ok !== true) {
1504
+ setError(`HTTP ${res.status}${json?.error ? ` · ${json.error}` : ''}`)
1505
+ return
1506
+ }
1507
+ setError(null)
1508
+ setTick((n) => n + 1)
1509
+ } catch (err) {
1510
+ setError(String(err?.message ?? err))
1511
+ onError?.(String(err?.message ?? err))
1512
+ } finally {
1513
+ setBusy(false)
1514
+ }
1515
+ }
1516
+
1517
+ if (unavailable) {
1518
+ return h('div', { style: S.card }, '提议队列不可用:这次组合里存储没有打开(只读部署不会为了看队列去建库)。')
1519
+ }
1520
+ return h('div', null,
1521
+ h(Card, { title: '核心块提议' },
1522
+ h('div', { style: S.grid },
1523
+ h(KV, { k: '待批', v: summary?.pending ?? 0 }),
1524
+ h(KV, { k: '过时', v: summary?.stale ?? 0 }),
1525
+ h(KV, { k: '已应用', v: summary?.applied ?? 0 }),
1526
+ h(KV, { k: '最老待批', v: summary?.oldestAgeMs == null ? '—' : `${fmtAge(summary.oldestAgeMs)}前` }),
1527
+ ),
1528
+ h('div', { style: S.toolMeta, marginTop: '6px' },
1529
+ '批准权只在人这里:模型只能提交提议。批准后在下一轮注入里生效。'),
1530
+ ),
1531
+ error && h('div', { style: S.banner(C.err) }, `决策失败:${error}`),
1532
+ !writable && h('div', { style: S.banner(C.idle) }, '面板只读,不能批准(config panel.writes: false)。'),
1533
+ items.length === 0
1534
+ ? h('div', { style: S.card }, '没有提议。模型认为该改核心块时,会先在这里排队等你批准。')
1535
+ : items.map((item) => h(ProposalRow, {
1536
+ key: item.id,
1537
+ item,
1538
+ writable,
1539
+ busy,
1540
+ onDecide: decide,
1541
+ })),
1542
+ h(Card, { title: '领域包' },
1543
+ h('div', { style: S.grid },
1544
+ h(KV, { k: '包数', v: domains.length }),
1545
+ h(KV, { k: '已批准', v: domains.filter((d) => d.status === 'active').length }),
1546
+ h(KV, { k: '本次注入', v: injectedDomains.length === 0 ? '无' : injectedDomains.join(', ') }),
1547
+ ),
1548
+ h('div', { style: S.toolMeta, marginTop: '6px' },
1549
+ '只有 approved(active)的包会被注入,且要打分过线;详情永不注入,模型需要时用 domain_detail 读。'),
1550
+ ),
1551
+ domains.length === 0
1552
+ ? h('div', { style: S.card }, '还没有领域包。用 `node scripts/seed-domains.mjs --apply` 写入四个起始草稿(只写 draft,不激活)。')
1553
+ : domains.map((pack) => h(DomainRow, {
1554
+ key: pack.domainId,
1555
+ pack,
1556
+ injected: injectedDomains.includes(pack.domainId),
1557
+ writable,
1558
+ busy,
1559
+ onStatus: setDomainStatus,
1560
+ })),
1561
+ // ── the six tacit classes ───────────────────────────────────────────────
1562
+ h(Card, { title: '暗知识(六类)' },
1563
+ knowledge === null || knowledge.unavailable === true
1564
+ ? h('div', { style: S.toolMeta }, '还没有捕获到暗知识;它来自抽取通道,不是手写的。')
1565
+ : h('div', null,
1566
+ h('div', { style: S.grid },
1567
+ h(KV, { k: '条目', v: (knowledge.kinds ?? []).reduce((sum, row) => sum + row.total, 0) }),
1568
+ h(KV, { k: '证据', v: knowledge.evidence ?? 0 }),
1569
+ h(KV, { k: '可晋升', v: knowledge.eligible ?? 0 }),
1570
+ h(KV, { k: '已晋升', v: knowledge.promotions ?? 0 }),
1571
+ ),
1572
+ h('div', { style: S.grid, marginTop: '6px' },
1573
+ h(KV, { k: `${knowledge.retrievals?.days ?? 7}天检索`, v: knowledge.retrievals?.total ?? 0 }),
1574
+ h(KV, { k: '命中率', v: knowledge.retrievals?.hitRate === null || knowledge.retrievals?.hitRate === undefined
1575
+ ? '—' : `${Math.round(knowledge.retrievals.hitRate * 100)}%` }),
1576
+ h(KV, { k: '注入命中', v: knowledge.retrievals?.injected ?? 0 }),
1577
+ h(KV, { k: '拒答', v: knowledge.retrievals?.refused ?? 0 }),
1578
+ ),
1579
+ (knowledge.kinds ?? []).length > 0 && h('div', { style: S.toolMeta, marginTop: '6px' },
1580
+ knowledge.kinds.map((row) => `${row.kind} ${row.active}/${row.total}`).join(' ')),
1581
+ ),
1582
+ h('div', { style: S.toolMeta, marginTop: '6px' },
1583
+ '晋升只产生提议,不会直接写块;只有 contract / persona 两类可以晋升。'),
1584
+ ),
1585
+ )
1586
+ }
1587
+
1588
+ const TIMELINE_URL = '/memvault/api/timeline'
1589
+
1590
+ /** Colour of one flow event, by what it means rather than which table it came from. */
1591
+ const flowTone = (kind) => {
1592
+ if (kind === 'knowledge') return C.warn
1593
+ if (kind === 'proposal') return C.brand
1594
+ if (kind === 'decision') return C.ok
1595
+ if (kind === 'retrieval') return C.muted
1596
+ if (kind.startsWith('domain:approve') || kind.startsWith('domain:activate')) return C.ok
1597
+ if (kind.startsWith('domain:deactivate') || kind.startsWith('domain:stale')) return C.idle
1598
+ return C.muted
1599
+ }
1600
+
1601
+ const truncate = (text, max) => {
1602
+ const value = String(text ?? '')
1603
+ return value.length > max ? `${value.slice(0, Math.max(1, max - 1))}…` : value
1604
+ }
1605
+
1606
+ /** One number on the top strip. The unit goes in `sub`, never in the number. */
1607
+ function BoardStat({ label, value, sub, tone = C.brand }) {
1608
+ return h('div', { style: { ...S.card, marginBottom: 0, padding: '10px 12px' } },
1609
+ h('div', { style: { fontSize: '10.5px', color: C.muted, letterSpacing: '.08em', textTransform: 'uppercase' } }, label),
1610
+ h('div', { style: { fontSize: '22px', fontWeight: 650, lineHeight: 1.3, color: tone } }, String(value)),
1611
+ sub ? h('div', { style: { fontSize: '11px', color: C.muted } }, sub) : null,
1612
+ )
1613
+ }
1614
+
1615
+ /**
1616
+ * The map: four fixed columns and nothing else.
1617
+ *
1618
+ * A force simulation would look livelier and mean nothing — the columns are the
1619
+ * pipeline (a block is what gets injected, a pack is workspace background, a
1620
+ * knowledge row is what was captured, a proposal is what waits for a human), and a
1621
+ * fixed layout keeps that reading stable across reloads.
1622
+ */
1623
+ const MAP = { width: 780, height: 300, rowH: 50, nodeW: 164, nodeH: 38 }
1624
+ const MAP_COLUMNS = [
1625
+ { key: 'blocks', x: 6, title: '核心块 → 注入' },
1626
+ { key: 'domains', x: 204, title: '领域包 → 背景' },
1627
+ { key: 'knowledge', x: 402, title: '暗知识 → 检索' },
1628
+ { key: 'proposals', x: 600, title: '提议 → 人批' },
1629
+ ]
1630
+
1631
+ function buildMapModel({ blocks, domains, knowledge, proposals }) {
1632
+ const nodes = []
1633
+ const edges = []
1634
+ const byCol = { blocks: 0, domains: 0, knowledge: 0, proposals: 0 }
1635
+ const columnOf = (key) => MAP_COLUMNS.find((column) => column.key === key)
1636
+ const add = (col, id, label, sub, tone) => {
1637
+ const row = byCol[col]
1638
+ const column = columnOf(col)
1639
+ if (row >= 4 || !column) return null
1640
+ byCol[col] += 1
1641
+ const node = { id, col, label: truncate(label, 18), sub: truncate(sub, 24), tone, x: column.x, y: 40 + row * MAP.rowH }
1642
+ nodes.push(node)
1643
+ return node
1644
+ }
1645
+ const find = (id) => nodes.find((node) => node.id === id)
1646
+
1647
+ const blockList = Array.isArray(blocks) ? blocks : []
1648
+ blockList.slice(0, 4).forEach((block) => {
1649
+ add('blocks', `block:${block.label}`, block.label, `${String(block.value ?? '').length} 字符`, C.brand)
1650
+ })
1651
+ if (blockList.length > 4) add('blocks', 'blocks:more', `+${blockList.length - 4} 块`, '预算外', C.idle)
1652
+
1653
+ const packs = Array.isArray(domains) ? domains : []
1654
+ const approved = packs.filter((pack) => pack.status === 'active')
1655
+ ;(approved.length > 0 ? approved : packs).slice(0, 4).forEach((pack) => {
1656
+ const gates = Array.isArray(pack.gates) ? pack.gates.length : 0
1657
+ add('domains', `domain:${pack.domainId}`, pack.domainId,
1658
+ `${pack.status}${gates > 0 ? ` · 闸门 ${gates}` : ''}`,
1659
+ pack.status === 'active' ? C.ok : C.idle)
1660
+ })
1661
+
1662
+ const kinds = knowledge?.kinds ?? []
1663
+ kinds.slice(0, 4).forEach((row) => {
1664
+ add('knowledge', `knowledge:${row.kind}`, row.kind, `${row.active}/${row.total} 在用 · 证据 ${row.used ?? 0}`, C.warn)
1665
+ })
1666
+ if (kinds.length > 4) add('knowledge', 'knowledge:more', `+${kinds.length - 4} 类`, '', C.idle)
1667
+
1668
+ const pending = proposals?.summary?.pending ?? 0
1669
+ const stale = proposals?.summary?.stale ?? 0
1670
+ const items = proposals?.items ?? []
1671
+ if (pending + stale === 0) {
1672
+ add('proposals', 'proposals:none', '空队列', '没有待批提议', C.idle)
1673
+ } else {
1674
+ add('proposals', 'proposals:pending', `${pending} 待批`, '等待人决定', C.brand)
1675
+ if (stale > 0) add('proposals', 'proposals:stale', `${stale} 过时`, '基线已变', C.idle)
1676
+ }
1677
+ items.filter((item) => item.status === 'pending').slice(0, 2).forEach((item) => {
1678
+ add('proposals', `proposal:${item.id}`, item.label, `${item.change_kind} · 待批`, C.brand)
1679
+ })
1680
+
1681
+ // Edges carry meaning: "this proposal would rewrite that block", "this class has
1682
+ // earned a promotion", "this pack is what put that gate in the prompt".
1683
+ for (const item of items.filter((entry) => entry.status === 'pending').slice(0, 3)) {
1684
+ const from = find(`proposal:${item.id}`) ?? find('proposals:pending')
1685
+ const to = find(`block:${item.label}`)
1686
+ if (from && to) edges.push({ from, to, tone: C.brand, dashed: false, label: '拟改' })
1687
+ }
1688
+ for (const row of kinds.slice(0, 4)) {
1689
+ const to = find(`block:learned-${row.kind}`)
1690
+ const from = find(`knowledge:${row.kind}`)
1691
+ if (from && to) edges.push({ from, to, tone: C.warn, dashed: true, label: '晋升' })
1692
+ }
1693
+ for (const pack of approved.slice(0, 3)) {
1694
+ if ((pack.gates ?? []).length > 0) {
1695
+ const from = find(`domain:${pack.domainId}`)
1696
+ const to = find('proposals:pending') ?? find('knowledge:contract')
1697
+ if (from && to) edges.push({ from, to, tone: C.idle, dashed: true, label: '闸门' })
1698
+ }
1699
+ }
1700
+ return { nodes, edges }
1701
+ }
1702
+
1703
+ function KnowledgeMap({ model, selected, onPick }) {
1704
+ const { nodes, edges } = model
1705
+ const edgePath = (edge) => {
1706
+ const x1 = edge.from.x + MAP.nodeW
1707
+ const y1 = edge.from.y + MAP.nodeH / 2
1708
+ const x2 = edge.to.x
1709
+ const y2 = edge.to.y + MAP.nodeH / 2
1710
+ const mid = (x1 + x2) / 2
1711
+ return `M ${x1} ${y1} C ${mid} ${y1}, ${mid} ${y2}, ${x2} ${y2}`
1712
+ }
1713
+ return h('svg', {
1714
+ viewBox: `0 0 ${MAP.width} ${MAP.height}`,
1715
+ style: { width: '100%', height: 'auto', display: 'block' },
1716
+ role: 'img',
1717
+ 'aria-label': '知识网络:核心块、领域包、暗知识与提议',
1718
+ },
1719
+ MAP_COLUMNS.map((column) => h('text', {
1720
+ key: `head-${column.key}`,
1721
+ x: column.x + 2, y: 18, fill: C.muted, fontSize: '10.5px', letterSpacing: '.06em',
1722
+ }, column.title)),
1723
+ edges.map((edge, index) => h('path', {
1724
+ key: `edge-${index}`,
1725
+ d: edgePath(edge),
1726
+ fill: 'none',
1727
+ stroke: edge.tone,
1728
+ strokeWidth: 1.2,
1729
+ strokeDasharray: edge.dashed ? '4 4' : 'none',
1730
+ opacity: 0.55,
1731
+ })),
1732
+ nodes.map((node) => h('g', {
1733
+ key: node.id,
1734
+ onClick: () => onPick(node),
1735
+ style: { cursor: 'pointer' },
1736
+ },
1737
+ h('rect', {
1738
+ x: node.x, y: node.y, width: MAP.nodeW, height: MAP.nodeH, rx: 9,
1739
+ fill: C.layer1,
1740
+ stroke: selected === node.id ? node.tone : C.border,
1741
+ strokeWidth: selected === node.id ? 2 : 1,
1742
+ }),
1743
+ h('rect', { x: node.x + 1, y: node.y + 8, width: 3, height: MAP.nodeH - 16, rx: 1.5, fill: node.tone }),
1744
+ h('text', { x: node.x + 12, y: node.y + 16, fill: C.fg, fontSize: '12px', fontWeight: 600 }, node.label),
1745
+ h('text', { x: node.x + 12, y: node.y + 30, fill: C.muted, fontSize: '10px' }, node.sub),
1746
+ )),
1747
+ )
1748
+ }
1749
+
1750
+ /** The flow: what happened, newest first, from tables that already record it. */
1751
+ function FlowTimeline({ events, error }) {
1752
+ if (error) return h('div', { style: S.banner(C.warn) }, `时间线读取失败:${error}`)
1753
+ if (!events || events.length === 0) {
1754
+ return h('div', { style: S.empty }, '还没有流转记录。捕获、提议、批准、领域激活都会出现在这里。')
1755
+ }
1756
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '1px' } },
1757
+ events.slice(0, 24).map((event, index) => h('div', {
1758
+ key: `${event.at}-${index}`,
1759
+ style: {
1760
+ display: 'grid', gridTemplateColumns: '52px 74px 1fr', gap: '8px', alignItems: 'baseline',
1761
+ padding: '3px 0', borderBottom: `1px solid ${C.border}`,
1762
+ },
1763
+ },
1764
+ h('span', { style: S.hint }, (() => {
1765
+ const date = new Date(event.at)
1766
+ return Number.isNaN(date.getTime()) ? '—' : date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
1767
+ })()),
1768
+ h('span', { style: { ...S.badge(flowTone(event.kind)), fontSize: '10px' } }, truncate(event.kind, 12)),
1769
+ h('span', { style: { minWidth: 0 } },
1770
+ h('span', { style: { fontWeight: 500 } }, truncate(event.label, 28)),
1771
+ event.detail ? h('span', { style: { ...S.hint, marginLeft: '6px' } }, truncate(event.detail, 48)) : null),
1772
+ )),
1773
+ )
1774
+ }
1775
+
1776
+ /**
1777
+ * The overview board.
1778
+ *
1779
+ * Four numbers, the map, the flow, and nothing that needs a second screen. Every
1780
+ * value comes from a read-only route: this view cannot change state, which is why
1781
+ * it is safe to make it the landing tab.
1782
+ */
1783
+ function BoardView({ data, writable, onError, onOpen }) {
1784
+ const [flow, setFlow] = useState(null)
1785
+ const [flowError, setFlowError] = useState(null)
1786
+ const [shelf, setShelf] = useState({ domains: [], active: [] })
1787
+ const [knowledge, setKnowledge] = useState(null)
1788
+ const [proposals, setProposals] = useState({ items: [], summary: null })
1789
+ const [selected, setSelected] = useState(null)
1790
+
1791
+ useEffect(() => {
1792
+ let alive = true
1793
+ const load = async () => {
1794
+ try {
1795
+ const [proposalRes, domainRes, knowledgeRes, timelineRes] = await Promise.all([
1796
+ fetch(`${PROPOSALS_URL}?status=all&limit=50`),
1797
+ fetch(DOMAIN_URL),
1798
+ fetch(KNOWLEDGE_URL),
1799
+ fetch(TIMELINE_URL),
1800
+ ])
1801
+ const [proposalJson, domainJson, knowledgeJson, timelineJson] = await Promise.all([
1802
+ proposalRes.json().catch(() => null),
1803
+ domainRes.json().catch(() => null),
1804
+ knowledgeRes.json().catch(() => null),
1805
+ timelineRes.json().catch(() => null),
1806
+ ])
1807
+ if (!alive) return
1808
+ if (proposalJson?.ok === true) setProposals({ items: proposalJson.items ?? [], summary: proposalJson.summary ?? null })
1809
+ if (domainJson?.ok === true) setShelf({ domains: domainJson.domains ?? [], active: domainJson.active ?? [] })
1810
+ if (knowledgeJson?.ok === true) setKnowledge(knowledgeJson)
1811
+ if (timelineJson?.ok === true) { setFlow(timelineJson.events ?? []); setFlowError(null) }
1812
+ else setFlowError(timelineJson?.error ?? `HTTP ${timelineRes.status}`)
1813
+ } catch (err) {
1814
+ if (alive) setFlowError(String(err?.message ?? err))
1815
+ onError?.(String(err?.message ?? err))
1816
+ }
1817
+ }
1818
+ load()
1819
+ const timer = setInterval(load, POLL_MS)
1820
+ return () => { alive = false; clearInterval(timer) }
1821
+ }, [])
1822
+
1823
+ const read = data?.read
1824
+ const blocks = data?.blocks ?? []
1825
+ const pending = proposals.summary?.pending ?? 0
1826
+ const stale = proposals.summary?.stale ?? 0
1827
+ const gateCount = shelf.domains.reduce((sum, pack) => sum + (Array.isArray(pack.gates) ? pack.gates.length : 0), 0)
1828
+ const knowledgeTotal = (knowledge?.kinds ?? []).reduce((sum, row) => sum + row.total, 0)
1829
+ const model = buildMapModel({ blocks, domains: shelf.domains, knowledge, proposals })
1830
+
1831
+ const detail = () => {
1832
+ if (!selected) return null
1833
+ const [kind, ...rest] = selected.id.split(':')
1834
+ if (kind === 'block') {
1835
+ const block = blocks.find((entry) => entry.label === rest.join(':'))
1836
+ return block && h('div', { style: S.block },
1837
+ h('div', { style: S.blockHead }, h('span', { style: S.tag }, block.label), h('span', { style: S.hint }, '注入内容(前 300 字)')),
1838
+ h('div', { style: S.body }, truncate(block.value, 300)))
1839
+ }
1840
+ if (kind === 'domain') {
1841
+ const pack = shelf.domains.find((entry) => entry.domainId === rest.join(':'))
1842
+ return pack && h('div', { style: S.block },
1843
+ h('div', { style: S.blockHead }, h('span', { style: S.tag }, pack.domainId),
1844
+ h('span', { style: S.badge(DOMAIN_STATUS_TONE[pack.status] ?? C.muted) }, pack.status),
1845
+ shelf.active.includes(pack.domainId) && h('span', { style: S.badge(C.brand) }, '本次注入')),
1846
+ h('div', { style: S.body }, truncate(pack.indexText, 240)),
1847
+ (pack.gates ?? []).length > 0 && h('div', { style: S.hint }, `闸门:${pack.gates.map((gate) => gate.id).join(' / ')}`))
1848
+ }
1849
+ if (kind === 'knowledge') {
1850
+ const row = (knowledge?.kinds ?? []).find((entry) => entry.kind === rest.join(':'))
1851
+ return row && h('div', { style: S.block },
1852
+ h('div', { style: S.blockHead }, h('span', { style: S.tag }, row.kind),
1853
+ h('span', { style: S.hint }, `共 ${row.total} · 在用 ${row.active} · 待定 ${row.proposed}`)),
1854
+ h('div', { style: S.hint }, `被检索 ${row.used} 次 · 被反驳 ${row.refuted} 次。晋升只产生提议,需要你在「进化」页批准。`))
1855
+ }
1856
+ const item = proposals.items.find((entry) => entry.id === rest.join(':'))
1857
+ return item && h('div', { style: S.block },
1858
+ h('div', { style: S.blockHead }, h('span', { style: S.tag }, item.label),
1859
+ h('span', { style: S.badge(item.status === 'pending' ? C.brand : C.muted) }, item.status)),
1860
+ h('div', { style: { ...S.hint, marginBottom: '4px' } }, `${item.change_kind} · 由 ${item.proposer} 提议`),
1861
+ h('div', { style: S.body }, truncate(item.proposed_value, 240)))
1862
+ }
1863
+
1864
+ return h(Fragment, null,
1865
+ h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '10px', marginBottom: '14px' } },
1866
+ h(BoardStat, { label: '注入', value: read ? `${read.renderedChars}` : '—',
1867
+ sub: read ? `${read.blockCount} 块 / ${read.maxChars} 字符上限` : '',
1868
+ tone: (read?.droppedBlocks ?? 0) > 0 ? C.warn : C.brand }),
1869
+ h(BoardStat, { label: '待批提议', value: pending, sub: stale > 0 ? `${stale} 条已过时` : '没有过时基线',
1870
+ tone: pending > 0 ? C.brand : C.muted }),
1871
+ h(BoardStat, { label: '开放闸门', value: gateCount,
1872
+ sub: shelf.active.length > 0 ? `注入中:${shelf.active.join(', ')}` : '没有领域包被注入',
1873
+ tone: gateCount > 0 ? C.warn : C.muted }),
1874
+ h(BoardStat, { label: '暗知识', value: knowledgeTotal,
1875
+ sub: `${knowledge?.evidence ?? 0} 条证据 · ${knowledge?.eligible ?? 0} 条可晋升`,
1876
+ tone: knowledgeTotal > 0 ? C.ok : C.muted }),
1877
+ ),
1878
+ h('div', { style: { display: 'grid', gridTemplateColumns: 'minmax(0, 3fr) minmax(0, 2fr)', gap: '14px', alignItems: 'start' } },
1879
+ h(Card, { title: '知识网络' },
1880
+ h(KnowledgeMap, { model, selected: selected?.id ?? null, onPick: setSelected }),
1881
+ h('div', { style: { ...S.hint, marginTop: '4px' } },
1882
+ '实线 = 提议拟改该块;虚线 = 晋升或闸门。点节点看内容。'),
1883
+ detail()),
1884
+ h(Card, { title: '流转(最近 24 条)' },
1885
+ h(FlowTimeline, { events: flow, error: flowError }),
1886
+ h('div', { style: { ...S.rowActions, marginTop: '8px' } },
1887
+ h('button', { style: S.small(C.muted), onClick: () => onOpen('memories') }, '打开记忆'),
1888
+ h('button', { style: S.small(C.muted), onClick: () => onOpen('proposals') }, '去进化')),
1889
+ ),
1890
+ ),
1891
+ )
1892
+ }
1893
+
1299
1894
  function MemoryPanel() {
1300
- const [view, setView] = useState('blocks')
1895
+ // The board is the landing tab: it is read-only, so it can be the first thing a
1896
+ // reader sees without any risk of a stray write.
1897
+ const [view, setView] = useState('board')
1301
1898
  // Set by "查看产出的记忆": the ids a diagnostic reported, handed to the browse
1302
1899
  // view as its filter (the key remounts it, so the filter is applied on mount).
1303
1900
  const [memoryIds, setMemoryIds] = useState('')
@@ -1305,6 +1902,7 @@ function MemoryPanel() {
1305
1902
  const [data, setData] = useState(null)
1306
1903
  const [error, setError] = useState(null)
1307
1904
  const [writeError, setWriteError] = useState(null)
1905
+ const [knowledge, setKnowledge] = useState(null)
1308
1906
  const [busy, setBusy] = useState(false)
1309
1907
 
1310
1908
  const load = async (force) => {
@@ -1413,10 +2011,14 @@ function MemoryPanel() {
1413
2011
  !writable && h('div', { style: S.banner(C.idle) }, '面板当前为只读(config panel.writes: false)。'),
1414
2012
 
1415
2013
  h('div', { style: { ...S.rowActions, marginBottom: '12px' } },
2014
+ h('button', {
2015
+ style: S.small(view === 'board' ? C.brand : C.muted, view === 'board'),
2016
+ onClick: () => setView('board'),
2017
+ }, '总览'),
1416
2018
  h('button', {
1417
2019
  style: S.small(view === 'blocks' ? C.brand : C.muted, view === 'blocks'),
1418
2020
  onClick: () => setView('blocks'),
1419
- }, '概览'),
2021
+ }, '注入'),
1420
2022
  h('button', {
1421
2023
  style: S.small(view === 'memories' ? C.brand : C.muted, view === 'memories'),
1422
2024
  onClick: () => setView('memories'),
@@ -1425,9 +2027,18 @@ function MemoryPanel() {
1425
2027
  style: S.small(view === 'structure' ? C.brand : C.muted, view === 'structure'),
1426
2028
  onClick: () => setView('structure'),
1427
2029
  }, '结构'),
2030
+ h('button', {
2031
+ style: S.small(view === 'proposals' ? C.brand : C.muted, view === 'proposals'),
2032
+ onClick: () => setView('proposals'),
2033
+ }, (data?.proposals?.pending ?? 0) > 0 ? `进化 (${data.proposals.pending})` : '进化'),
1428
2034
  ),
1429
2035
 
1430
- view === 'blocks' ? h(Fragment, null,
2036
+ view === 'board' ? h(BoardView, {
2037
+ data,
2038
+ writable,
2039
+ onError: setWriteError,
2040
+ onOpen: setView,
2041
+ }) : view === 'blocks' ? h(Fragment, null,
1431
2042
  h(Card, { title: '存储与注入' },
1432
2043
  h('div', { style: S.grid },
1433
2044
  h(KV, { k: '库文件', v: read?.dbPath }),
@@ -1537,7 +2148,8 @@ function MemoryPanel() {
1537
2148
  ),
1538
2149
  ),
1539
2150
  ) : view === 'structure' ? h(StructureView, { onError: setError })
1540
- : h(MemoriesView, { key: memoryIds, onError: setError, initialIds: memoryIds }),
2151
+ : view === 'proposals' ? h(ProposalsView, { writable, onError: setError })
2152
+ : h(MemoriesView, { key: memoryIds, onError: setError, initialIds: memoryIds }),
1541
2153
  ),
1542
2154
  )
1543
2155
  }
@@ -1722,7 +2334,14 @@ function apply(ctx) {
1722
2334
  }
1723
2335
  }
1724
2336
 
1725
- module.exports = { name: NAME, inject: ['slots'], apply }
2337
+ /**
2338
+ * Export shape the loader expects. `__internal` exists for the bundle test: the
2339
+ * panel is a hand-written CommonJS factory, so the only way to render the board in
2340
+ * a test is to hand it the same components the host would mount. The cost is a few
2341
+ * bytes in the bundle; the benefit is that a broken layout fails `npm test` instead
2342
+ * of showing up as a blank tab after a restart.
2343
+ */
2344
+ module.exports = { name: NAME, inject: ['slots'], apply, __internal: { BoardView, buildMapModel, FlowTimeline, KnowledgeMap } }
1726
2345
 
1727
2346
  return module.exports; } });
1728
- //# sourceSHA256=9e5dd40c233914b7
2347
+ //# sourceSHA256=2cd042854c3930a6