@kingsleyasher/dsh-knowledge-base 3.1.5 → 3.1.7
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/PROJECT-RECORD.en.md +798 -782
- package/PROJECT-RECORD.md +809 -793
- package/README.md +107 -109
- package/README.zh-CN.md +7 -7
- package/RELEASE.en.md +21 -0
- package/RELEASE.md +21 -0
- package/VERSIONING.en.md +1 -1
- package/VERSIONING.md +1 -1
- package/cordis.patch.yml +88 -88
- package/docs/client/PROJECT-RECORD.en.md +6 -2
- package/docs/client/PROJECT-RECORD.md +6 -2
- package/package.json +76 -78
- package/packages/kb-core/src/kbcore.js +68 -29
- package/packages/kb-core/src/workbench.js +31 -3
- package/packages/kb-service/desktop-files.js +23 -5
- package/packages/kb-service/host-adapter.js +6 -5
- package/packages/kb-service/host-request-auth.js +31 -0
- package/packages/kb-service/host-updates.js +21 -91
- package/packages/kb-service/legacy-ports.js +5 -1
- package/packages/kb-service/safe-update.js +5 -5
- package/packages/kb-service/service.js +8 -2
- package/packages/kb-service/tool-definitions.json +5 -0
- package/packages/kb-service/tool-router.js +22 -6
- package/src/client/index.js +4982 -4975
- package/src/host/index.js +33 -18
- package/src/host/updates.js +5 -5
- package/tools/kb-transactional-update.py +11 -19
- package/NPM-EDITION.md +0 -12
package/package.json
CHANGED
|
@@ -1,78 +1,76 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@kingsleyasher/dsh-knowledge-base",
|
|
3
|
-
"version": "3.1.
|
|
4
|
-
"description": "个人知识工作台:可控隐私、首次设置、目录地图、快速收集、阅读摘录、引用问答与按需备份。",
|
|
5
|
-
"icon": "./src/client/capture-icon.svg",
|
|
6
|
-
"type": "module",
|
|
7
|
-
"main": "./src/host/index.js",
|
|
8
|
-
"exports": {
|
|
9
|
-
".": "./src/host/index.js",
|
|
10
|
-
"./package.json": "./package.json",
|
|
11
|
-
"./client": "./src/client/index.js",
|
|
12
|
-
"./core": "./packages/kb-core/index.js",
|
|
13
|
-
"./contracts": "./packages/kb-contracts/index.js",
|
|
14
|
-
"./service": "./packages/kb-service/index.js"
|
|
15
|
-
},
|
|
16
|
-
"files": [
|
|
17
|
-
"src",
|
|
18
|
-
"cordis.patch.yml",
|
|
19
|
-
"README.md",
|
|
20
|
-
"PARSING-PREVIEW.md",
|
|
21
|
-
"WORKBENCH.md",
|
|
22
|
-
"BETA4.md",
|
|
23
|
-
"browser-extension",
|
|
24
|
-
"presets",
|
|
25
|
-
"skills",
|
|
26
|
-
"tools/kb-pdf-pages.py",
|
|
27
|
-
"tools/kb-local-model.py",
|
|
28
|
-
"tools/kb-transactional-update.py",
|
|
29
|
-
"BETA7.md",
|
|
30
|
-
"BETA8.md",
|
|
31
|
-
"BETA9.md",
|
|
32
|
-
"VERSIONING.md",
|
|
33
|
-
"PROJECT-RECORD.md",
|
|
34
|
-
"RETRIEVAL.md",
|
|
35
|
-
"PERFORMANCE.md",
|
|
36
|
-
"RELEASE.md",
|
|
37
|
-
"RELEASE.en.md",
|
|
38
|
-
"PROJECT-RECORD.en.md",
|
|
39
|
-
"WORKBENCH.en.md",
|
|
40
|
-
"VERSIONING.en.md",
|
|
41
|
-
"EXISTING-FRAMEWORK-OPTIMIZATION.md",
|
|
42
|
-
"packages/kb-core",
|
|
43
|
-
"packages/kb-contracts",
|
|
44
|
-
"packages/kb-service",
|
|
45
|
-
"runtime/python",
|
|
46
|
-
"docs",
|
|
47
|
-
"ARCHITECTURE.md",
|
|
48
|
-
"ARCHITECTURE.en.md",
|
|
49
|
-
"DEVELOPMENT.md",
|
|
50
|
-
"DEVELOPMENT.en.md",
|
|
51
|
-
"MONOREPO.md",
|
|
52
|
-
"PRIVACY.md",
|
|
53
|
-
"SECURITY.md",
|
|
54
|
-
"THIRD-PARTY-NOTICES.md",
|
|
55
|
-
"CONTRIBUTING.md"
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
"./
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
"
|
|
73
|
-
|
|
74
|
-
"
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
"homepage": "https://github.com/KingsleyAsher/Personal-Knowledge-Base"
|
|
78
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@kingsleyasher/dsh-knowledge-base",
|
|
3
|
+
"version": "3.1.7",
|
|
4
|
+
"description": "个人知识工作台:可控隐私、首次设置、目录地图、快速收集、阅读摘录、引用问答与按需备份。",
|
|
5
|
+
"icon": "./src/client/capture-icon.svg",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./src/host/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/host/index.js",
|
|
10
|
+
"./package.json": "./package.json",
|
|
11
|
+
"./client": "./src/client/index.js",
|
|
12
|
+
"./core": "./packages/kb-core/index.js",
|
|
13
|
+
"./contracts": "./packages/kb-contracts/index.js",
|
|
14
|
+
"./service": "./packages/kb-service/index.js"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"src",
|
|
18
|
+
"cordis.patch.yml",
|
|
19
|
+
"README.md",
|
|
20
|
+
"PARSING-PREVIEW.md",
|
|
21
|
+
"WORKBENCH.md",
|
|
22
|
+
"BETA4.md",
|
|
23
|
+
"browser-extension",
|
|
24
|
+
"presets",
|
|
25
|
+
"skills",
|
|
26
|
+
"tools/kb-pdf-pages.py",
|
|
27
|
+
"tools/kb-local-model.py",
|
|
28
|
+
"tools/kb-transactional-update.py",
|
|
29
|
+
"BETA7.md",
|
|
30
|
+
"BETA8.md",
|
|
31
|
+
"BETA9.md",
|
|
32
|
+
"VERSIONING.md",
|
|
33
|
+
"PROJECT-RECORD.md",
|
|
34
|
+
"RETRIEVAL.md",
|
|
35
|
+
"PERFORMANCE.md",
|
|
36
|
+
"RELEASE.md",
|
|
37
|
+
"RELEASE.en.md",
|
|
38
|
+
"PROJECT-RECORD.en.md",
|
|
39
|
+
"WORKBENCH.en.md",
|
|
40
|
+
"VERSIONING.en.md",
|
|
41
|
+
"EXISTING-FRAMEWORK-OPTIMIZATION.md",
|
|
42
|
+
"packages/kb-core",
|
|
43
|
+
"packages/kb-contracts",
|
|
44
|
+
"packages/kb-service",
|
|
45
|
+
"runtime/python",
|
|
46
|
+
"docs",
|
|
47
|
+
"ARCHITECTURE.md",
|
|
48
|
+
"ARCHITECTURE.en.md",
|
|
49
|
+
"DEVELOPMENT.md",
|
|
50
|
+
"DEVELOPMENT.en.md",
|
|
51
|
+
"MONOREPO.md",
|
|
52
|
+
"PRIVACY.md",
|
|
53
|
+
"SECURITY.md",
|
|
54
|
+
"THIRD-PARTY-NOTICES.md",
|
|
55
|
+
"CONTRIBUTING.md"
|
|
56
|
+
],
|
|
57
|
+
"dsh": {
|
|
58
|
+
"bundle": {
|
|
59
|
+
"patch": [
|
|
60
|
+
"./cordis.patch.yml",
|
|
61
|
+
"./presets/01-knowledge-agent.patch.yml"
|
|
62
|
+
]
|
|
63
|
+
},
|
|
64
|
+
"client": {
|
|
65
|
+
"inject": [
|
|
66
|
+
"slots"
|
|
67
|
+
],
|
|
68
|
+
"platform": "web"
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
"license": "MIT",
|
|
72
|
+
"repository": {
|
|
73
|
+
"type": "git",
|
|
74
|
+
"url": "git+https://github.com/KingsleyAsher/Personal-Knowledge-Base.git"
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -26,7 +26,7 @@ import {catalogActive,readCatalog,refreshCatalog,classifyOriginal} from './file-
|
|
|
26
26
|
import { CLASSIFICATION_VERSION } from './file-classification.js'
|
|
27
27
|
|
|
28
28
|
// 版本单一来源:package.json 的 version 必须与此一致(详见 INSTALL 说明)
|
|
29
|
-
export const VERSION = '3.1.
|
|
29
|
+
export const VERSION = '3.1.7'
|
|
30
30
|
|
|
31
31
|
export const REQUIRED_FIELDS = ['title', 'type', 'tags', 'status', 'updated']
|
|
32
32
|
export const SCHEMA_VERSION = 1
|
|
@@ -1480,6 +1480,11 @@ export function createCore(cfg, logger) {
|
|
|
1480
1480
|
return { state: res.state, entries: [] }
|
|
1481
1481
|
}
|
|
1482
1482
|
|
|
1483
|
+
let lastBlockedIndexDrop
|
|
1484
|
+
function indexDropDetails(error) {
|
|
1485
|
+
return { reason: error.code, needsConfirmation: true, confirmationToken: error.confirmationToken, oldCount: error.oldCount, newCount: error.newCount }
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1483
1488
|
async function writeIndex(conf, entries, options = {}) {
|
|
1484
1489
|
const payload = { generatedAt: nowIso(), meta: await indexMetaOf(conf, entries), entries }
|
|
1485
1490
|
const root = kbRootOf(conf)
|
|
@@ -1492,13 +1497,20 @@ export function createCore(cfg, logger) {
|
|
|
1492
1497
|
if (disk.error || disk.fingerprint !== fingerprintOf(entries)) throw Object.assign(new Error('扫描期间文件发生变化或不可读,旧索引已保留'), { code: 'source-unstable' })
|
|
1493
1498
|
const old = await readIndexState(indexPath(root))
|
|
1494
1499
|
if (old.state === 'ok' && Array.isArray(old.value?.entries) && typeof old.value.meta?.kbId === 'string' && old.value.meta.kbId.trim() && old.value.meta.kbId !== payload.meta.kbId) throw Object.assign(new Error('索引知识库身份不匹配'), { code: 'index-kbid-mismatch' })
|
|
1495
|
-
const
|
|
1500
|
+
const oldEntries = Array.isArray(old.value?.entries) ? old.value.entries.filter(e => e && typeof e.path === 'string') : []
|
|
1501
|
+
const oldCount = oldEntries.length
|
|
1496
1502
|
const drop = oldCount - entries.length
|
|
1497
|
-
const token = sha12(Buffer.from(JSON.stringify([old.value?.meta?.fingerprint, payload.meta.fingerprint, oldCount, entries.length])))
|
|
1498
1503
|
const nextPaths = new Set(entries.map(e => e.path)), known = new Set(options.knownRemovedPaths || [])
|
|
1499
|
-
const onlyKnownRemovals = known.size > 0 &&
|
|
1500
|
-
if ((oldCount > 0 && !entries.length || oldCount >= 20 && drop / oldCount >= .2) &&
|
|
1501
|
-
|
|
1504
|
+
const onlyKnownRemovals = known.size > 0 && oldEntries.every(e => nextPaths.has(e.path) || known.has(e.path))
|
|
1505
|
+
if ((oldCount > 0 && !entries.length || oldCount >= 20 && drop / oldCount >= .2) && !onlyKnownRemovals) {
|
|
1506
|
+
const token = sha12(Buffer.from(JSON.stringify([root, payload.meta.kbId, payload.meta.excludes, old.value?.generatedAt, fingerprintOf(oldEntries), payload.meta.fingerprint, oldCount, entries.length])))
|
|
1507
|
+
if (options.confirmDrop !== token) {
|
|
1508
|
+
if (lastBlockedIndexDrop !== token) {
|
|
1509
|
+
lastBlockedIndexDrop = token
|
|
1510
|
+
await writeLog('warn', `索引待确认 reason=index-drop-confirmation oldCount=${oldCount} newCount=${entries.length}`)
|
|
1511
|
+
}
|
|
1512
|
+
throw Object.assign(new Error('条目数量明显下降,已保留旧索引;请核对差异后确认'), { code: 'index-drop-confirmation', confirmationToken: token, oldCount, newCount: entries.length })
|
|
1513
|
+
}
|
|
1502
1514
|
}
|
|
1503
1515
|
if (options.snapshot !== false && old.state === 'ok' && validIndexPayload(old.value) && old.value.meta?.kbId === payload.meta.kbId) {
|
|
1504
1516
|
const directory = path.join(path.dirname(indexPath(root)), 'snapshots')
|
|
@@ -1513,6 +1525,7 @@ export function createCore(cfg, logger) {
|
|
|
1513
1525
|
const current = await getConfigFresh(), live = await diskFingerprint(conf, true)
|
|
1514
1526
|
if (kbRootOf(current) !== root || current.revision !== conf.revision || live.error || live.fingerprint !== payload.meta.fingerprint) throw Object.assign(new Error('提交前资料或配置已改变,旧索引已保留'), { code: 'source-unstable' })
|
|
1515
1527
|
} })
|
|
1528
|
+
lastBlockedIndexDrop = undefined
|
|
1516
1529
|
indexCache.delete(indexPath(root)); ioMetrics.indexCommits++
|
|
1517
1530
|
return payload
|
|
1518
1531
|
}
|
|
@@ -1605,8 +1618,10 @@ export function createCore(cfg, logger) {
|
|
|
1605
1618
|
if (mode !== 'unchanged') await writeLog('info', `索引维护 ${mode} entries=${entries.length} added=${diff.added.length} removed=${diff.removed.length} changed=${diff.changed.length}`)
|
|
1606
1619
|
return { ok: true, execution: 'ok', indexWritten: mode !== 'unchanged', mode, entries: entries.length, diff, ...maintenanceState }
|
|
1607
1620
|
} catch (e) {
|
|
1608
|
-
|
|
1609
|
-
|
|
1621
|
+
const blocked = e.code === 'index-drop-confirmation'
|
|
1622
|
+
maintenanceState = { ...maintenanceState, state: 'failed', reason: e.code || 'maintenance-failed', detail: e.message,
|
|
1623
|
+
...(blocked ? indexDropDetails(e) : { needsConfirmation: undefined, confirmationToken: undefined, oldCount: undefined, newCount: undefined }) }
|
|
1624
|
+
if (!blocked) await writeLog('warn', `索引维护未替换旧索引 reason=${maintenanceState.reason}`)
|
|
1610
1625
|
return { ok: false, ...maintenanceState, indexPreserved: true }
|
|
1611
1626
|
}
|
|
1612
1627
|
})) } finally { await releaseConfigLock(configLock.token) }
|
|
@@ -2250,7 +2265,7 @@ export function createCore(cfg, logger) {
|
|
|
2250
2265
|
}
|
|
2251
2266
|
|
|
2252
2267
|
// ── 检查(R2:走同一把库级锁;R4:扫描不完整不覆盖完整索引)─────────
|
|
2253
|
-
async function checkLocked(conf) {
|
|
2268
|
+
async function checkLocked(conf, { confirmDrop, recover } = {}) {
|
|
2254
2269
|
const root = kbRootOf(conf)
|
|
2255
2270
|
const health = await healthOf(conf)
|
|
2256
2271
|
// 一次读取、一个快照(旧实现 readIndex + indexFreshness 各读一遍)
|
|
@@ -2284,7 +2299,7 @@ export function createCore(cfg, logger) {
|
|
|
2284
2299
|
// 故这里不再产生 noId 缺陷(见 PATCH-NOTES-派生id.md)。
|
|
2285
2300
|
if (parsed.valid === false) defects.push({ kind: 'frontmatter', path: entry.path, detail: parsed.reason ?? 'frontmatter 非法' })
|
|
2286
2301
|
}
|
|
2287
|
-
for (const p0 of removed) defects.push({ kind: 'missingFile', path: p0, detail: '
|
|
2302
|
+
for (const p0 of removed) defects.push({ kind: 'missingFile', path: p0, detail: '上一次索引里有、本次扫描未纳入,请核对文件及检索排除范围' })
|
|
2288
2303
|
for (const err of fresh.scanErrors) defects.push({ kind: 'scanError', path: '-', detail: err })
|
|
2289
2304
|
// P1-D:索引过期单独记为缺陷(kbId/排除规则/格式/内容指纹任一不符)
|
|
2290
2305
|
if (!freshness.fresh && snap.state === 'ok') {
|
|
@@ -2292,11 +2307,27 @@ export function createCore(cfg, logger) {
|
|
|
2292
2307
|
}
|
|
2293
2308
|
|
|
2294
2309
|
// R4:扫描不完整(scanErrors>0)时**不得**用不完整结果覆盖索引 —— 保留旧索引并标 partial
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2310
|
+
let indexWritten = false
|
|
2311
|
+
let indexWriteBlocked
|
|
2312
|
+
if (fresh.scanErrors.length === 0) {
|
|
2313
|
+
try {
|
|
2314
|
+
await writeIndex(conf, fresh.entries, { confirmDrop })
|
|
2315
|
+
indexWritten = true
|
|
2316
|
+
} catch (error) {
|
|
2317
|
+
if (error.code !== 'index-drop-confirmation') throw error
|
|
2318
|
+
indexWriteBlocked = indexDropDetails(error)
|
|
2319
|
+
defects.push({ kind: error.code, path: toPosix(path.relative(root, indexPath(root))), detail: `${error.message}。用户确认后,用 kb_check 的 confirmDrop 参数提交 indexWriteBlocked.confirmationToken` })
|
|
2320
|
+
}
|
|
2321
|
+
} else defects.push({ kind: 'index-not-written', path: '-.kbmeta/index', detail: `扫描不完整(${fresh.scanErrors.length} 处错误),已保留旧索引、未覆盖;恢复记录不删除` })
|
|
2322
|
+
let recovery
|
|
2323
|
+
const todo = path.join(root, '.kbmeta', 'recover-todo.log')
|
|
2324
|
+
if (recover) {
|
|
2325
|
+
if (!existsSync(todo)) recovery = { ok: true, consumed: 0 }
|
|
2326
|
+
else if (indexWritten) recovery = await consumeRecoverTodo(todo)
|
|
2327
|
+
else recovery = { ok: false, consumed: 0, kept: true, ...(indexWriteBlocked ?? { reason: 'scan-incomplete', scanErrors: fresh.scanErrors }) }
|
|
2328
|
+
}
|
|
2329
|
+
if (!indexWritten && !indexWriteBlocked && existsSync(todo)) {
|
|
2330
|
+
await writeLog('warn', '索引未写入:recover-todo 保留待下次消费')
|
|
2300
2331
|
}
|
|
2301
2332
|
|
|
2302
2333
|
const result = {
|
|
@@ -2309,8 +2340,10 @@ export function createCore(cfg, logger) {
|
|
|
2309
2340
|
links: { skipped: fresh.skippedLinks ?? [], policy: conf.followLinks ? 'follow-inside' : 'deny' },
|
|
2310
2341
|
diff: { added, removed, changed },
|
|
2311
2342
|
defects,
|
|
2312
|
-
rebuiltAt: nowIso(),
|
|
2343
|
+
...(indexWritten ? { rebuiltAt: nowIso() } : {}),
|
|
2313
2344
|
indexWritten,
|
|
2345
|
+
...(indexWriteBlocked ? { indexWriteBlocked } : {}),
|
|
2346
|
+
...(recovery ? { recover: recovery } : {}),
|
|
2314
2347
|
// 语义保持 P1 原样:index.fresh 反映**本次检查开始时**的新鲜度;
|
|
2315
2348
|
// 本次是否已重建看 indexWritten / rebuiltAt(不要用"重建后状态"掩盖过期事实)
|
|
2316
2349
|
index: { fresh: freshness.fresh, reason: freshness.reason, detail: freshness.detail ?? '' },
|
|
@@ -2319,42 +2352,48 @@ export function createCore(cfg, logger) {
|
|
|
2319
2352
|
return result
|
|
2320
2353
|
}
|
|
2321
2354
|
|
|
2322
|
-
async function check(args) {
|
|
2355
|
+
async function check(args = {}) {
|
|
2323
2356
|
const gate = await configGate()
|
|
2324
2357
|
if (!gate.ok) {
|
|
2325
|
-
return { ok: false, execution: 'error', quality: 'unknown', defects: [], reason: gate.refusal.reason, detail: gate.refusal.detail
|
|
2358
|
+
return { ok: false, execution: 'error', quality: 'unknown', defects: [], reason: gate.refusal.reason, detail: gate.refusal.detail,
|
|
2359
|
+
...(args.recover ? { recover: { ...gate.refusal, consumed: 0 } } : {}) }
|
|
2326
2360
|
}
|
|
2327
2361
|
const conf = gate.conf
|
|
2328
2362
|
const root = kbRootOf(conf)
|
|
2329
2363
|
// R2:维护性写入(rebuild)必须与 create/update 共用同一把锁,否则会覆盖对方刚写的索引
|
|
2330
|
-
return withLock(root, () => withKbLock(root, 'check', () => checkLocked(conf)))
|
|
2364
|
+
return withLock(root, () => withKbLock(root, 'check', () => checkLocked(conf, args)))
|
|
2331
2365
|
}
|
|
2332
2366
|
|
|
2333
2367
|
/** 公开检查入口(含 recover):工具与自检共用同一条路径,避免"测的不是跑的" */
|
|
2334
2368
|
async function checkEntry(args = {}) {
|
|
2335
|
-
if (args && args.recover) {
|
|
2336
|
-
const drained = await drainRecoverTodo()
|
|
2337
|
-
const result = await check({ ...args, rebuild: true })
|
|
2338
|
-
return { ...result, recover: drained }
|
|
2339
|
-
}
|
|
2340
2369
|
return check(args ?? {})
|
|
2341
2370
|
}
|
|
2342
2371
|
|
|
2372
|
+
async function consumeRecoverTodo(file) {
|
|
2373
|
+
const lines = (await readFile(file, 'utf8')).split('\n').filter(Boolean)
|
|
2374
|
+
await rm(file, { force: true })
|
|
2375
|
+
await writeLog('info', `recover-todo 已消费 ${lines.length} 条并重建索引`)
|
|
2376
|
+
return { ok: true, consumed: lines.length }
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2343
2379
|
/** 已持锁版本的恢复消费(公开入口与自动消费者共用,避免两处逻辑漂移) */
|
|
2344
2380
|
async function drainRecoverTodoLocked(conf) {
|
|
2345
2381
|
const root = kbRootOf(conf)
|
|
2346
2382
|
const file = path.join(root, '.kbmeta', 'recover-todo.log')
|
|
2347
2383
|
if (!existsSync(file)) return { ok: true, consumed: 0 }
|
|
2348
|
-
|
|
2349
|
-
|
|
2384
|
+
let rebuilt
|
|
2385
|
+
try {
|
|
2386
|
+
rebuilt = await reindexLocked(conf)
|
|
2387
|
+
} catch (error) {
|
|
2388
|
+
if (error.code !== 'index-drop-confirmation') throw error
|
|
2389
|
+
return { ok: false, consumed: 0, kept: true, ...indexDropDetails(error) }
|
|
2390
|
+
}
|
|
2350
2391
|
if (rebuilt.ok === false) {
|
|
2351
2392
|
// 扫描不完整:保留旧索引与恢复记录,等下次再消费(不假装恢复成功)
|
|
2352
2393
|
await writeLog('warn', `恢复未完成:扫描不完整(${(rebuilt.scanErrors ?? []).length} 处错误),索引与恢复记录均保留`)
|
|
2353
2394
|
return { ok: false, consumed: 0, kept: true, reason: rebuilt.reason, scanErrors: rebuilt.scanErrors ?? [] }
|
|
2354
2395
|
}
|
|
2355
|
-
|
|
2356
|
-
await writeLog('info', `recover-todo 已消费 ${lines.length} 条并重建索引`)
|
|
2357
|
-
return { ok: true, consumed: lines.length }
|
|
2396
|
+
return consumeRecoverTodo(file)
|
|
2358
2397
|
}
|
|
2359
2398
|
|
|
2360
2399
|
async function drainRecoverTodo() {
|
|
@@ -91,11 +91,24 @@ export function createWorkbench({ stateDir, getCore, getParsing = () => null, ge
|
|
|
91
91
|
const indexCompletedArchive = async b => {
|
|
92
92
|
invalidatePolicyCaches()
|
|
93
93
|
const result = await b.core.maintainIndex({ expectedKbId: b.st.kbId })
|
|
94
|
-
if (!result.ok)
|
|
94
|
+
if (!result.ok) {
|
|
95
|
+
const error = fail(result.reason || 'INDEX_REBUILD_FAILED', result.detail || result.reason)
|
|
96
|
+
if (result.needsConfirmation) Object.assign(error, {
|
|
97
|
+
needsConfirmation: true, confirmationToken: result.confirmationToken, oldCount: result.oldCount, newCount: result.newCount,
|
|
98
|
+
})
|
|
99
|
+
throw error
|
|
100
|
+
}
|
|
95
101
|
await relations(await binding(b.st.kbId), { force: true }); await retrieval.automatic()
|
|
96
102
|
}
|
|
97
103
|
const upgrades=createSystemUpgrades({binding,catalog:async()=>Object.entries(TEMPLATES).map(([name,content])=>({path:'_模板/'+name,content,version:VERSION})),runtime:getUpgradeContext,retrieval,now})
|
|
98
|
-
const
|
|
104
|
+
const catalogPrivatePaths=new WeakMap()
|
|
105
|
+
const catalogPrivate = (catalog,file) => {
|
|
106
|
+
if(!catalog)return false
|
|
107
|
+
let paths=catalogPrivatePaths.get(catalog)
|
|
108
|
+
if(!paths){paths=new Set(catalog.files.filter(f=>f.private).map(f=>f.path));catalogPrivatePaths.set(catalog,paths)}
|
|
109
|
+
return paths.has(file)
|
|
110
|
+
}
|
|
111
|
+
const isPrivate = (b, file) => catalogPrivate(b.fileCatalog,file) || privateRootOf(file, b.privateDirs) !== null || deliverablePrivate(b.deliverables, file) || Boolean(groupFor(b.indexPolicy, file)?.files.some(f => privateRootOf(f.normal, b.privateDirs) !== null))
|
|
99
112
|
const visible = (b, file, question = false, includePrivate = false) => (!question || !policyExcluded(b.indexPolicy, file)) && (!isPrivate(b, file) || (question ? b.preferences.showPrivate && b.preferences.allowPrivateQuestions && includePrivate : b.preferences.showPrivate))
|
|
100
113
|
const indexable = (b, file) => !policyExcluded(b.indexPolicy, file)
|
|
101
114
|
function redactReferences(b, file, text, allowPrivate = b.preferences.showPrivate) {
|
|
@@ -493,7 +506,22 @@ export function createWorkbench({ stateDir, getCore, getParsing = () => null, ge
|
|
|
493
506
|
return policyService.set(b, args)
|
|
494
507
|
}
|
|
495
508
|
if (args.op === 'inbox.list') return { ok: true, ...await capture(b, { ...args, op: 'capture.inbox-files' }) }
|
|
496
|
-
if (args.op === 'inbox.complete') {
|
|
509
|
+
if (args.op === 'inbox.complete') {
|
|
510
|
+
const result = await capture(b, { ...args, op: 'capture.complete', expectedRevision: (await userData(b)).revision })
|
|
511
|
+
let indexSync
|
|
512
|
+
try {
|
|
513
|
+
await indexCompletedArchive(b)
|
|
514
|
+
indexSync = { ok: true }
|
|
515
|
+
} catch (error) {
|
|
516
|
+
indexSync = { ok: false, reason: error.code || 'INDEX_SYNC_FAILED', detail: error.message }
|
|
517
|
+
if (error.needsConfirmation) {
|
|
518
|
+
const { confirmationToken, oldCount, newCount } = error
|
|
519
|
+
Object.assign(indexSync, { needsConfirmation: true, confirmationToken, oldCount, newCount,
|
|
520
|
+
detail: `${error.message}。请用 kb_check 核对差异,用户确认后再提交确认令牌` })
|
|
521
|
+
} else log('warn', '收件箱已登记,索引同步未完成:' + indexSync.reason)
|
|
522
|
+
}
|
|
523
|
+
return { ok: true, ...result, indexSync }
|
|
524
|
+
}
|
|
497
525
|
if (args.op.startsWith('retrieval.')) return { ok:true, ...await retrieval.dispatch(b,args,caller) }
|
|
498
526
|
if (args.op === 'search.expand') {const out=await retrieval.expand(b,args);return {ok:true,...out,text:redactReferences(b,args.path,out.text)}}
|
|
499
527
|
if (args.op === 'atlas.relations.status') return { ok: true, sync: relationIndex.status(b) }
|
|
@@ -69,8 +69,19 @@ export async function createDesktopFiles({root,privateDir,desktopRoot,core,withL
|
|
|
69
69
|
return {id:p,path:p,name:path.posix.basename(p),type:s.isDirectory()?'directory':'file',mime:s.isFile()?mimeOf(p):undefined,size:Number(s.size),modifiedAt:Number(s.mtimeMs),revision:version(s),access:accessInfo,protected:system,hasChildren:s.isDirectory(),...(original?{category:original.category,kind:original.kind,original:true}:{})};
|
|
70
70
|
}
|
|
71
71
|
const listCache=new Map(),LIST_CACHE_MS=15000,LIST_CACHE_MAX=64;
|
|
72
|
+
let listCacheRevision=0;
|
|
73
|
+
function invalidate(paths){
|
|
74
|
+
listCacheRevision++;
|
|
75
|
+
if(!Array.isArray(paths)){listCache.clear();return;}
|
|
76
|
+
const scopes=paths.map(p=>String(p).replaceAll('\\','/').toLowerCase());
|
|
77
|
+
for(const key of listCache.keys()){
|
|
78
|
+
const parent=key.slice(0,key.lastIndexOf('|')).toLowerCase();
|
|
79
|
+
if(scopes.some(p=>!p||parent===p||parent.startsWith(p+'/')||path.posix.dirname(p)===(parent||'.')))listCache.delete(key);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
72
82
|
const dirSignature=async folder=>{const s=await lstat(folder,{bigint:true});return [String(s.dev),String(s.ino),String(s.mtimeNs),String(s.ctimeNs)].join(':')};
|
|
73
83
|
async function list(parent='',offset=0,limit=500,sort='name-asc'){
|
|
84
|
+
const revision=listCacheRevision;
|
|
74
85
|
const folder=parent?await checked(parent):base,signature=await dirSignature(folder);
|
|
75
86
|
const cacheKey=parent+'|'+sort,catalog=getCatalog(),hint=[signature,indexPolicySignature(base),catalog?`${catalog.revision??0}:${catalog.policyRevision??0}`:'-',showPrivate()?'1':'0',getPrivateDirs().join('|')].join('#');
|
|
76
87
|
const cached=listCache.get(cacheKey);
|
|
@@ -79,14 +90,20 @@ export async function createDesktopFiles({root,privateDir,desktopRoot,core,withL
|
|
|
79
90
|
return {items:cached.items.slice(offset,offset+limit),nextOffset:offset+limit<cached.items.length?offset+limit:undefined,total:cached.items.length};
|
|
80
91
|
}
|
|
81
92
|
const matcher=policyMatcher(),rows=[];
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
93
|
+
const entries=await readdir(folder,{withFileTypes:true});
|
|
94
|
+
async function readEntry(entry){
|
|
95
|
+
const p=parent?parent+'/'+entry.name:entry.name;
|
|
96
|
+
if(entry.name.startsWith('.')||entry.isSymbolicLink()||privatePath(p)||['node_modules','索引层'].includes(entry.name))return;
|
|
97
|
+
try{return await info(p,matcher,path.join(folder,entry.name));}
|
|
98
|
+
catch(error){if(!['FORBIDDEN','LINK_DENIED','EACCES','ENOENT'].includes(error.code))throw error;}
|
|
99
|
+
}
|
|
100
|
+
for(let i=0;i<entries.length;i+=16){
|
|
101
|
+
const batch=await Promise.all(entries.slice(i,i+16).map(readEntry));
|
|
102
|
+
rows.push(...batch.filter(Boolean));
|
|
86
103
|
}
|
|
87
104
|
const nameOrder=(a,b)=>a.name.localeCompare(b.name,'zh-CN',{numeric:true});
|
|
88
105
|
rows.sort((a,b)=>(a.type===b.type?0:a.type==='directory'?-1:1)||(sort==='modified-desc'?b.modifiedAt-a.modifiedAt:sort==='modified-asc'?a.modifiedAt-b.modifiedAt:sort==='name-desc'?-nameOrder(a,b):nameOrder(a,b))||nameOrder(a,b));
|
|
89
|
-
if(rows.length<=3000){if(listCache.size>=LIST_CACHE_MAX)listCache.delete(listCache.keys().next().value);listCache.set(cacheKey,{hint,at:Date.now(),items:rows});}
|
|
106
|
+
if(revision===listCacheRevision&&rows.length<=3000){if(listCache.size>=LIST_CACHE_MAX)listCache.delete(listCache.keys().next().value);listCache.set(cacheKey,{hint,at:Date.now(),items:rows});}
|
|
90
107
|
return {items:rows.slice(offset,offset+limit),nextOffset:offset+limit<rows.length?offset+limit:undefined,total:rows.length};
|
|
91
108
|
}
|
|
92
109
|
async function walk(parent='',out=[],depth=0){
|
|
@@ -460,6 +477,7 @@ export async function createDesktopFiles({root,privateDir,desktopRoot,core,withL
|
|
|
460
477
|
if(intent?.operation==='backupDelete')await finishBackupDelete(match[1],intent);
|
|
461
478
|
}
|
|
462
479
|
return {
|
|
480
|
+
invalidate,
|
|
463
481
|
async sourceFromStage(id,caller){const s=stages.get(id);if(!s||s.caller!==caller||!s.final)throw error('FORBIDDEN');const data=await readFile(s.file);if(hash(data)!==s.hash)throw error('CONFLICT','暂存原件已变化');return {data,name:s.name,bytes:data.length,external:true};},
|
|
464
482
|
async recoverReceipt(operationId){const intent=await readJson(path.join(storage,'operations',operationId,'intent.json'),null);if(intent?.operation==='backupDelete')return finishBackupDelete(operationId,intent);const receipt=await readJson(path.join(storage,'operations',operationId,'committed.json'),null);if(receipt)return receipt;if(intent?.operation==='trash'){
|
|
465
483
|
const dir=await trashDir(operationId),item=await readJson(path.join(dir,'manifest.json'),null);
|
|
@@ -16,6 +16,7 @@ import {startDesktopHostLinks} from './desktop-host-links.js'
|
|
|
16
16
|
import {createParseSourceAuthority} from '../kb-core/src/parse-source-authority.js'
|
|
17
17
|
import {createFlowWorkspaceManager} from '../kb-core/src/flow-workspace.js'
|
|
18
18
|
import {registerHostAssets} from './host-assets.js'
|
|
19
|
+
import {withHostRequestAuth} from './host-request-auth.js'
|
|
19
20
|
// Called only by an explicitly configured Host. It never starts an embedded writer.
|
|
20
21
|
export async function mountServiceHost(ctx, config, { isLiveKnowledgeGrant, gatewayApply, createCitationGuard, build, getFlowWorkspace,installApi,legacyStateDir,profileDir,library,python='python' }) {
|
|
21
22
|
const definitions = JSON.parse(await readFile(new URL('./tool-definitions.json', import.meta.url),'utf8'))
|
|
@@ -87,7 +88,7 @@ export async function mountServiceHost(ctx, config, { isLiveKnowledgeGrant, gate
|
|
|
87
88
|
const systemPrompt = ctx.get('systemPrompt')
|
|
88
89
|
if (typeof systemPrompt?.context === 'function') ctx.effect(() => systemPrompt.context({ name:'kb:parse-policy', order:600, interpolate:false, text:parseRule }), 'kb-service: parse policy')
|
|
89
90
|
for (const definition of definitions) {
|
|
90
|
-
const entry = { name:definition.name, description:definition.name === 'kb_parse' ? parseRule + '用 action=submit、kind=asr/ocr 和 sourcePath/sourceRef/sourceRel 提交;action=providers 查询当前设置,job/result 查看任务和结果。providerId 不能覆盖会话默认服务。' : '共享知识库服务:'+definition.name, parameters:definition.parameters,
|
|
91
|
+
const entry = { name:definition.name, description:definition.name === 'kb_parse' ? parseRule + '用 action=submit、kind=asr/ocr 和 sourcePath/sourceRef/sourceRel 提交;action=providers 查询当前设置,job/result 查看任务和结果。providerId 不能覆盖会话默认服务。' : definition.description ?? '共享知识库服务:'+definition.name, parameters:definition.parameters,
|
|
91
92
|
output:{schema:definition.outputSchema,render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]},
|
|
92
93
|
isConcurrencySafe:()=>false,
|
|
93
94
|
async execute(input,exec) {const invoke=async()=>{const target=desktopLinks?.clientForAgent(exec?.agent);if(target===null)return {ok:false,reason:'HOST_UNAVAILABLE'};return routing.run(target??primaryClient,async()=>{
|
|
@@ -137,15 +138,15 @@ export async function mountServiceHost(ctx, config, { isLiveKnowledgeGrant, gate
|
|
|
137
138
|
return send(res,200,await client.call('adapter.dispatch',{operation:body},{requestId:body.requestId??randomUUID()}))
|
|
138
139
|
}catch(e){send(res,200,{ok:false,code:e.code??'HOST_UNAVAILABLE',error:e.message})}
|
|
139
140
|
};
|
|
140
|
-
ctx.effect(()=>installApi?installApi(apiHandler):server.register({kind:'exact',path:'/kb-core/api',handler:apiHandler}),'kb-service: existing workbench API')
|
|
141
|
-
ctx.effect(()=>server.register({kind:'exact',path:'/kb-core/workbench-events',handler:async(req,res)=>{
|
|
141
|
+
ctx.effect(()=>installApi?installApi(apiHandler):server.register({kind:'exact',path:'/kb-core/api',handler:withHostRequestAuth(ctx,apiHandler)}),'kb-service: existing workbench API')
|
|
142
|
+
ctx.effect(()=>server.register({kind:'exact',path:'/kb-core/workbench-events',handler:withHostRequestAuth(ctx,async(req,res)=>{
|
|
142
143
|
if(req.method!=='GET'||!sameOrigin(req))return send(res,403,{ok:false})
|
|
143
144
|
res.writeHead(200,{'content-type':'text/event-stream','cache-control':'no-store'})
|
|
144
145
|
res.write(': shared-service\n\n')
|
|
145
146
|
const off=client.subscribe(event=>res.write('data: '+JSON.stringify(event)+'\n\n'))
|
|
146
|
-
try{await client.call('events.subscribe')}catch(e){res.write('data: '+JSON.stringify({type:'service-unavailable',code:e.code})+'\n\n')}
|
|
147
147
|
const heartbeat=setInterval(()=>res.write(': heartbeat\n\n'),15000);res.once('close',()=>{off();clearInterval(heartbeat)})
|
|
148
|
-
|
|
148
|
+
try{await client.call('events.subscribe')}catch(e){if(!res.destroyed)res.write('data: '+JSON.stringify({type:'service-unavailable',code:e.code})+'\n\n')}
|
|
149
|
+
})}),'kb-service: existing workbench events')
|
|
149
150
|
}
|
|
150
151
|
return {mode:'service',tools:definitions.map(x=>x.name),client}
|
|
151
152
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
function rejectionStatus(connection, request) {
|
|
2
|
+
if (typeof connection?.admit === 'function') {
|
|
3
|
+
const admission = connection.admit(request)
|
|
4
|
+
if (admission?.peer) return admission.peer.principal?.kind === 'owner' ? undefined : 403
|
|
5
|
+
return admission?.rejection === 403 ? 403 : 401
|
|
6
|
+
}
|
|
7
|
+
// Older web hosts authenticate their browser session through this method.
|
|
8
|
+
if (typeof connection?.requestRejection === 'function') {
|
|
9
|
+
const rejection = connection.requestRejection(request)
|
|
10
|
+
if (rejection === undefined || rejection === 401 || rejection === 403) return rejection
|
|
11
|
+
}
|
|
12
|
+
return 503
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function withHostRequestAuth(ctx, handler) {
|
|
16
|
+
return (request, response) => {
|
|
17
|
+
let status
|
|
18
|
+
try {
|
|
19
|
+
status = rejectionStatus(ctx.get('connection'), request)
|
|
20
|
+
} catch {
|
|
21
|
+
status = 503
|
|
22
|
+
}
|
|
23
|
+
response.setHeader('cache-control', 'no-store')
|
|
24
|
+
if (status === undefined) return handler(request, response)
|
|
25
|
+
|
|
26
|
+
response.statusCode = status
|
|
27
|
+
response.setHeader('content-type', 'application/json; charset=utf-8')
|
|
28
|
+
const code = status === 401 ? 'HOST_AUTH_REQUIRED' : status === 403 ? 'FORBIDDEN' : 'HOST_AUTH_UNAVAILABLE'
|
|
29
|
+
response.end(JSON.stringify({ ok: false, code }))
|
|
30
|
+
}
|
|
31
|
+
}
|