@kingsleyasher/dsh-knowledge-base 3.1.5 → 3.1.6
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/NPM-EDITION.md +1 -1
- package/PROJECT-RECORD.en.md +792 -782
- package/PROJECT-RECORD.md +803 -793
- package/README.md +109 -109
- package/README.zh-CN.md +7 -7
- package/RELEASE.en.md +5 -0
- package/RELEASE.md +5 -0
- package/VERSIONING.en.md +1 -1
- package/VERSIONING.md +1 -1
- package/cordis.patch.yml +88 -88
- package/package.json +78 -78
- package/packages/kb-core/src/kbcore.js +23 -7
- package/packages/kb-core/src/workbench.js +13 -2
- package/packages/kb-service/host-updates.js +1 -1
- package/packages/kb-service/safe-update.js +104 -104
- package/packages/kb-service/tool-router.js +9 -5
- package/src/client/index.js +4976 -4975
- package/src/host/index.js +5 -1
package/package.json
CHANGED
|
@@ -1,78 +1,78 @@
|
|
|
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
|
-
"NPM-EDITION.md"
|
|
57
|
-
],
|
|
58
|
-
"dsh": {
|
|
59
|
-
"bundle": {
|
|
60
|
-
"patch": [
|
|
61
|
-
"./cordis.patch.yml",
|
|
62
|
-
"./presets/01-knowledge-agent.patch.yml"
|
|
63
|
-
]
|
|
64
|
-
},
|
|
65
|
-
"client": {
|
|
66
|
-
"inject": [
|
|
67
|
-
"slots"
|
|
68
|
-
],
|
|
69
|
-
"platform": "web"
|
|
70
|
-
}
|
|
71
|
-
},
|
|
72
|
-
"license": "MIT",
|
|
73
|
-
"repository": {
|
|
74
|
-
"type": "git",
|
|
75
|
-
"url": "git+https://github.com/KingsleyAsher/Personal-Knowledge-Base.git"
|
|
76
|
-
},
|
|
77
|
-
"homepage": "https://github.com/KingsleyAsher/Personal-Knowledge-Base"
|
|
78
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@kingsleyasher/dsh-knowledge-base",
|
|
3
|
+
"version": "3.1.6",
|
|
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
|
+
"NPM-EDITION.md"
|
|
57
|
+
],
|
|
58
|
+
"dsh": {
|
|
59
|
+
"bundle": {
|
|
60
|
+
"patch": [
|
|
61
|
+
"./cordis.patch.yml",
|
|
62
|
+
"./presets/01-knowledge-agent.patch.yml"
|
|
63
|
+
]
|
|
64
|
+
},
|
|
65
|
+
"client": {
|
|
66
|
+
"inject": [
|
|
67
|
+
"slots"
|
|
68
|
+
],
|
|
69
|
+
"platform": "web"
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
"license": "MIT",
|
|
73
|
+
"repository": {
|
|
74
|
+
"type": "git",
|
|
75
|
+
"url": "git+https://github.com/KingsleyAsher/Personal-Knowledge-Base.git"
|
|
76
|
+
},
|
|
77
|
+
"homepage": "https://github.com/KingsleyAsher/Personal-Knowledge-Base"
|
|
78
|
+
}
|
|
@@ -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.6'
|
|
30
30
|
|
|
31
31
|
export const REQUIRED_FIELDS = ['title', 'type', 'tags', 'status', 'updated']
|
|
32
32
|
export const SCHEMA_VERSION = 1
|
|
@@ -2292,11 +2292,20 @@ export function createCore(cfg, logger) {
|
|
|
2292
2292
|
}
|
|
2293
2293
|
|
|
2294
2294
|
// R4:扫描不完整(scanErrors>0)时**不得**用不完整结果覆盖索引 —— 保留旧索引并标 partial
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2295
|
+
let indexWritten = false
|
|
2296
|
+
let indexWriteBlocked
|
|
2297
|
+
if (fresh.scanErrors.length === 0) {
|
|
2298
|
+
try {
|
|
2299
|
+
await writeIndex(conf, fresh.entries)
|
|
2300
|
+
indexWritten = true
|
|
2301
|
+
} catch (error) {
|
|
2302
|
+
if (error.code !== 'index-drop-confirmation') throw error
|
|
2303
|
+
indexWriteBlocked = { reason: error.code, oldCount: error.oldCount, newCount: error.newCount }
|
|
2304
|
+
defects.push({ kind: error.code, path: toPosix(path.relative(root, indexPath(root))), detail: error.message })
|
|
2305
|
+
}
|
|
2306
|
+
} else defects.push({ kind: 'index-not-written', path: '-.kbmeta/index', detail: `扫描不完整(${fresh.scanErrors.length} 处错误),已保留旧索引、未覆盖;恢复记录不删除` })
|
|
2298
2307
|
if (!indexWritten && existsSync(path.join(root, '.kbmeta', 'recover-todo.log'))) {
|
|
2299
|
-
await writeLog('warn', '
|
|
2308
|
+
await writeLog('warn', '索引未写入:recover-todo 保留待下次消费')
|
|
2300
2309
|
}
|
|
2301
2310
|
|
|
2302
2311
|
const result = {
|
|
@@ -2309,8 +2318,9 @@ export function createCore(cfg, logger) {
|
|
|
2309
2318
|
links: { skipped: fresh.skippedLinks ?? [], policy: conf.followLinks ? 'follow-inside' : 'deny' },
|
|
2310
2319
|
diff: { added, removed, changed },
|
|
2311
2320
|
defects,
|
|
2312
|
-
rebuiltAt: nowIso(),
|
|
2321
|
+
...(indexWritten ? { rebuiltAt: nowIso() } : {}),
|
|
2313
2322
|
indexWritten,
|
|
2323
|
+
...(indexWriteBlocked ? { indexWriteBlocked } : {}),
|
|
2314
2324
|
// 语义保持 P1 原样:index.fresh 反映**本次检查开始时**的新鲜度;
|
|
2315
2325
|
// 本次是否已重建看 indexWritten / rebuiltAt(不要用"重建后状态"掩盖过期事实)
|
|
2316
2326
|
index: { fresh: freshness.fresh, reason: freshness.reason, detail: freshness.detail ?? '' },
|
|
@@ -2346,7 +2356,13 @@ export function createCore(cfg, logger) {
|
|
|
2346
2356
|
const file = path.join(root, '.kbmeta', 'recover-todo.log')
|
|
2347
2357
|
if (!existsSync(file)) return { ok: true, consumed: 0 }
|
|
2348
2358
|
const lines = (await readFile(file, 'utf8')).split('\n').filter(Boolean)
|
|
2349
|
-
|
|
2359
|
+
let rebuilt
|
|
2360
|
+
try {
|
|
2361
|
+
rebuilt = await reindexLocked(conf)
|
|
2362
|
+
} catch (error) {
|
|
2363
|
+
if (error.code !== 'index-drop-confirmation') throw error
|
|
2364
|
+
return { ok: false, consumed: 0, kept: true, reason: error.code }
|
|
2365
|
+
}
|
|
2350
2366
|
if (rebuilt.ok === false) {
|
|
2351
2367
|
// 扫描不完整:保留旧索引与恢复记录,等下次再消费(不假装恢复成功)
|
|
2352
2368
|
await writeLog('warn', `恢复未完成:扫描不完整(${(rebuilt.scanErrors ?? []).length} 处错误),索引与恢复记录均保留`)
|
|
@@ -91,7 +91,7 @@ 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) throw fail('INDEX_REBUILD_FAILED', result.detail || result.reason)
|
|
94
|
+
if (!result.ok) throw fail(result.reason || 'INDEX_REBUILD_FAILED', result.detail || result.reason)
|
|
95
95
|
await relations(await binding(b.st.kbId), { force: true }); await retrieval.automatic()
|
|
96
96
|
}
|
|
97
97
|
const upgrades=createSystemUpgrades({binding,catalog:async()=>Object.entries(TEMPLATES).map(([name,content])=>({path:'_模板/'+name,content,version:VERSION})),runtime:getUpgradeContext,retrieval,now})
|
|
@@ -493,7 +493,18 @@ export function createWorkbench({ stateDir, getCore, getParsing = () => null, ge
|
|
|
493
493
|
return policyService.set(b, args)
|
|
494
494
|
}
|
|
495
495
|
if (args.op === 'inbox.list') return { ok: true, ...await capture(b, { ...args, op: 'capture.inbox-files' }) }
|
|
496
|
-
if (args.op === 'inbox.complete') {
|
|
496
|
+
if (args.op === 'inbox.complete') {
|
|
497
|
+
const result = await capture(b, { ...args, op: 'capture.complete', expectedRevision: (await userData(b)).revision })
|
|
498
|
+
let indexSync
|
|
499
|
+
try {
|
|
500
|
+
await indexCompletedArchive(b)
|
|
501
|
+
indexSync = { ok: true }
|
|
502
|
+
} catch (error) {
|
|
503
|
+
indexSync = { ok: false, reason: error.code || 'INDEX_SYNC_FAILED', detail: error.message }
|
|
504
|
+
log('warn', '收件箱已登记,索引同步未完成:' + indexSync.reason)
|
|
505
|
+
}
|
|
506
|
+
return { ok: true, ...result, indexSync }
|
|
507
|
+
}
|
|
497
508
|
if (args.op.startsWith('retrieval.')) return { ok:true, ...await retrieval.dispatch(b,args,caller) }
|
|
498
509
|
if (args.op === 'search.expand') {const out=await retrieval.expand(b,args);return {ok:true,...out,text:redactReferences(b,args.path,out.text)}}
|
|
499
510
|
if (args.op === 'atlas.relations.status') return { ok: true, sync: relationIndex.status(b) }
|
|
@@ -1,104 +1,104 @@
|
|
|
1
|
-
import path from 'node:path'
|
|
2
|
-
import { readFile, mkdir, writeFile, stat } from 'node:fs/promises'
|
|
3
|
-
import { createHash } from 'node:crypto'
|
|
4
|
-
import { spawn } from 'node:child_process'
|
|
5
|
-
import { resolveHostPython } from './host-python.js'
|
|
6
|
-
import { native } from './io.js'
|
|
7
|
-
import { readCandidateBuild } from './build.js'
|
|
8
|
-
|
|
9
|
-
// The worker and Python live outside the replaceable package. The receipt is
|
|
10
|
-
// durable, so losing the HTTP/HMR reply never means installation is repeated.
|
|
11
|
-
export function createSafeUpdate({ profileDir, packageRoot, quiesce, resume, withUpdateLock = task => task(), activate, activeBuild, installedRoot = path.join(profileDir, 'node_modules/@local/dsh-knowledge-base'), journalName = '.kb-safe-updates' }) {
|
|
12
|
-
let operation
|
|
13
|
-
const home = path.join(profileDir, journalName)
|
|
14
|
-
async function ensureHome(){const python=await resolveHostPython(packageRoot,{home:path.join(profileDir,'.kb-update-python')});await native(python,'private-dir',{path:home});return python}
|
|
15
|
-
async function invoke(action, args = []) {
|
|
16
|
-
const source = await readFile(path.join(packageRoot, 'tools/kb-transactional-update.py'))
|
|
17
|
-
const python=await ensureHome()
|
|
18
|
-
const script = path.join(home, 'installer-' + createHash('sha256').update(source).digest('hex') + '.py')
|
|
19
|
-
try { await writeFile(script, source, { flag: 'wx', mode: 0o600 }) } catch (e) { if (e.code !== 'EEXIST') throw e }
|
|
20
|
-
if (!(await readFile(script)).equals(source)) throw Error('Update worker integrity mismatch')
|
|
21
|
-
return await new Promise((resolve, reject) => {
|
|
22
|
-
const child = spawn(python, ['-I', '-X', 'utf8', script, action, '--profile', profileDir, ...args], { detached: true, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
23
|
-
let output = '', errors = ''
|
|
24
|
-
child.stdout.on('data', chunk => { if (output.length < 65536) output += chunk })
|
|
25
|
-
child.stderr.on('data', chunk => { if (errors.length < 4096) errors += chunk })
|
|
26
|
-
child.once('error', reject)
|
|
27
|
-
child.once('exit', code => {
|
|
28
|
-
try { const result = JSON.parse(output.trim().split('\n').at(-1)); if (code || !result.ok) throw Error(result.error || 'Update failed; backup retained'); resolve(result) }
|
|
29
|
-
catch (error) {
|
|
30
|
-
const message = error.message === 'An unresolved update requires recovery first'
|
|
31
|
-
? '检测到尚未完成的安装事务,需要先恢复该事务;未开始新安装。'
|
|
32
|
-
: error.message === 'Profile writer is busy; old installation unchanged'
|
|
33
|
-
? '其他安装进程正在写入配置,请等待其完成后重试;当前安装未改变。'
|
|
34
|
-
: code ? '安全更新未完成;旧版本或恢复备份已保留,请查看更新事务记录。' : error.message
|
|
35
|
-
reject(Object.assign(Error(message), { code: 'UPDATE_TRANSACTION_FAILED' }))
|
|
36
|
-
}
|
|
37
|
-
})
|
|
38
|
-
})
|
|
39
|
-
}
|
|
40
|
-
async function activateCommitted(committed) {
|
|
41
|
-
if (activeBuild?.buildId === committed.buildId && activeBuild.version === committed.version) {
|
|
42
|
-
return { ...committed, application:'applied' }
|
|
43
|
-
}
|
|
44
|
-
if (activate) {
|
|
45
|
-
try {
|
|
46
|
-
const result = await activate()
|
|
47
|
-
if (result && !result.restartReason && !result.pending?.length) return { ...committed, application:'applied' }
|
|
48
|
-
} catch {
|
|
49
|
-
// A committed candidate never goes through package installation again.
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
// Keep the existing adapter available if the Host did not replace it.
|
|
53
|
-
await resume?.()
|
|
54
|
-
return committed
|
|
55
|
-
}
|
|
56
|
-
return {
|
|
57
|
-
async prepare(prepared) {
|
|
58
|
-
if (operation) throw Error('另一个安全更新正在进行')
|
|
59
|
-
const expected = path.join(home, 'expected-' + (prepared.buildId || prepared.sha256) + '.json')
|
|
60
|
-
await ensureHome(); await writeFile(expected, JSON.stringify(prepared), { mode: 0o600 })
|
|
61
|
-
const plan = await invoke('prepare', ['--archive', prepared.spec, '--expected', expected])
|
|
62
|
-
return { ...prepared, ok: true, buildId: plan.buildId || prepared.buildId, safeInstall: true, hotActivation: Boolean(activate), transactionId: plan.transactionId }
|
|
63
|
-
},
|
|
64
|
-
install({ transactionId, expectedVersion }) {
|
|
65
|
-
if (operation) return operation
|
|
66
|
-
operation = (async () => {
|
|
67
|
-
const plan = JSON.parse(await readFile(path.join(home, 'transaction.json'), 'utf8'))
|
|
68
|
-
if (plan.work !== transactionId || plan.version !== expectedVersion) throw Error('更新事务已变化,请重新检查')
|
|
69
|
-
if (plan.phase === 'committed') return activateCommitted({ application:'restart-required', version:plan.version, buildId:plan.buildId, transactionId:plan.work })
|
|
70
|
-
if (plan.phase !== 'prepared') throw Error('该事务需要恢复,未重新开始安装')
|
|
71
|
-
// Must fail closed when the current runtime cannot prove quiescence.
|
|
72
|
-
if (!quiesce) throw Error('当前运行模式不支持安全停服,更新已延后,旧版未改动')
|
|
73
|
-
let committed
|
|
74
|
-
try {
|
|
75
|
-
committed = await withUpdateLock(async () => {
|
|
76
|
-
await quiesce()
|
|
77
|
-
return invoke('commit',['--transaction',transactionId])
|
|
78
|
-
})
|
|
79
|
-
} catch (error) {
|
|
80
|
-
const state = JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))
|
|
81
|
-
if (['rolled-back','prepared','aborted'].includes(state.phase)) await resume?.()
|
|
82
|
-
if (state.phase === 'prepared' && error.code === 'STATE_BUSY') {
|
|
83
|
-
return { application:'deferred', error:error.message, retryable:true }
|
|
84
|
-
}
|
|
85
|
-
throw error
|
|
86
|
-
}
|
|
87
|
-
return activateCommitted(committed)
|
|
88
|
-
})().finally(() => { operation = null })
|
|
89
|
-
return operation
|
|
90
|
-
},
|
|
91
|
-
async status() {
|
|
92
|
-
let plan
|
|
93
|
-
try{plan=JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))}catch(error){if(error.code!=='ENOENT')throw error;plan={phase:'none'}}
|
|
94
|
-
if(plan.phase==='publishing'&&!operation){try{await invoke('recover');plan=JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))}catch{/* live worker or recovery requires attention */}}
|
|
95
|
-
let writerBusy
|
|
96
|
-
try{await stat(path.join(profileDir,'package.json.lock'));writerBusy=true}catch(error){if(error.code!=='ENOENT')throw error;writerBusy=false}
|
|
97
|
-
let installedBuild
|
|
98
|
-
try{const build=await readCandidateBuild(installedRoot);installedBuild={version:build.version,buildId:build.buildId}}catch{/* incomplete package is never proof that retry is safe */}
|
|
99
|
-
return { phase: plan.phase, version: plan.version, buildId: plan.buildId, transactionId: plan.work, restartRequired: plan.phase === 'committed',
|
|
100
|
-
confirmationProtocol:1,operationActive:Boolean(operation),writerBusy,installedBuild,
|
|
101
|
-
canRetryLegacy:Boolean(installedBuild&&!operation&&!writerBusy&&['none','committed','aborted','rolled-back'].includes(plan.phase)) }
|
|
102
|
-
},
|
|
103
|
-
}
|
|
104
|
-
}
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { readFile, mkdir, writeFile, stat } from 'node:fs/promises'
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import { spawn } from 'node:child_process'
|
|
5
|
+
import { resolveHostPython } from './host-python.js'
|
|
6
|
+
import { native } from './io.js'
|
|
7
|
+
import { readCandidateBuild } from './build.js'
|
|
8
|
+
|
|
9
|
+
// The worker and Python live outside the replaceable package. The receipt is
|
|
10
|
+
// durable, so losing the HTTP/HMR reply never means installation is repeated.
|
|
11
|
+
export function createSafeUpdate({ profileDir, packageRoot, quiesce, resume, withUpdateLock = task => task(), activate, activeBuild, installedRoot = path.join(profileDir, 'node_modules/@local/dsh-knowledge-base'), journalName = '.kb-safe-updates' }) {
|
|
12
|
+
let operation
|
|
13
|
+
const home = path.join(profileDir, journalName)
|
|
14
|
+
async function ensureHome(){const python=await resolveHostPython(packageRoot,{home:path.join(profileDir,'.kb-update-python')});await native(python,'private-dir',{path:home});return python}
|
|
15
|
+
async function invoke(action, args = []) {
|
|
16
|
+
const source = await readFile(path.join(packageRoot, 'tools/kb-transactional-update.py'))
|
|
17
|
+
const python=await ensureHome()
|
|
18
|
+
const script = path.join(home, 'installer-' + createHash('sha256').update(source).digest('hex') + '.py')
|
|
19
|
+
try { await writeFile(script, source, { flag: 'wx', mode: 0o600 }) } catch (e) { if (e.code !== 'EEXIST') throw e }
|
|
20
|
+
if (!(await readFile(script)).equals(source)) throw Error('Update worker integrity mismatch')
|
|
21
|
+
return await new Promise((resolve, reject) => {
|
|
22
|
+
const child = spawn(python, ['-I', '-X', 'utf8', script, action, '--profile', profileDir, ...args], { detached: true, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
23
|
+
let output = '', errors = ''
|
|
24
|
+
child.stdout.on('data', chunk => { if (output.length < 65536) output += chunk })
|
|
25
|
+
child.stderr.on('data', chunk => { if (errors.length < 4096) errors += chunk })
|
|
26
|
+
child.once('error', reject)
|
|
27
|
+
child.once('exit', code => {
|
|
28
|
+
try { const result = JSON.parse(output.trim().split('\n').at(-1)); if (code || !result.ok) throw Error(result.error || 'Update failed; backup retained'); resolve(result) }
|
|
29
|
+
catch (error) {
|
|
30
|
+
const message = error.message === 'An unresolved update requires recovery first'
|
|
31
|
+
? '检测到尚未完成的安装事务,需要先恢复该事务;未开始新安装。'
|
|
32
|
+
: error.message === 'Profile writer is busy; old installation unchanged'
|
|
33
|
+
? '其他安装进程正在写入配置,请等待其完成后重试;当前安装未改变。'
|
|
34
|
+
: code ? '安全更新未完成;旧版本或恢复备份已保留,请查看更新事务记录。' : error.message
|
|
35
|
+
reject(Object.assign(Error(message), { code: 'UPDATE_TRANSACTION_FAILED' }))
|
|
36
|
+
}
|
|
37
|
+
})
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
async function activateCommitted(committed) {
|
|
41
|
+
if (activeBuild?.buildId === committed.buildId && activeBuild.version === committed.version) {
|
|
42
|
+
return { ...committed, application:'applied' }
|
|
43
|
+
}
|
|
44
|
+
if (activate) {
|
|
45
|
+
try {
|
|
46
|
+
const result = await activate()
|
|
47
|
+
if (result && !result.restartReason && !result.pending?.length) return { ...committed, application:'applied' }
|
|
48
|
+
} catch {
|
|
49
|
+
// A committed candidate never goes through package installation again.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
// Keep the existing adapter available if the Host did not replace it.
|
|
53
|
+
await resume?.()
|
|
54
|
+
return committed
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
async prepare(prepared) {
|
|
58
|
+
if (operation) throw Error('另一个安全更新正在进行')
|
|
59
|
+
const expected = path.join(home, 'expected-' + (prepared.buildId || prepared.sha256) + '.json')
|
|
60
|
+
await ensureHome(); await writeFile(expected, JSON.stringify(prepared), { mode: 0o600 })
|
|
61
|
+
const plan = await invoke('prepare', ['--archive', prepared.spec, '--expected', expected])
|
|
62
|
+
return { ...prepared, ok: true, buildId: plan.buildId || prepared.buildId, safeInstall: true, hotActivation: Boolean(activate), transactionId: plan.transactionId }
|
|
63
|
+
},
|
|
64
|
+
install({ transactionId, expectedVersion }) {
|
|
65
|
+
if (operation) return operation
|
|
66
|
+
operation = (async () => {
|
|
67
|
+
const plan = JSON.parse(await readFile(path.join(home, 'transaction.json'), 'utf8'))
|
|
68
|
+
if (plan.work !== transactionId || plan.version !== expectedVersion) throw Error('更新事务已变化,请重新检查')
|
|
69
|
+
if (plan.phase === 'committed') return activateCommitted({ application:'restart-required', version:plan.version, buildId:plan.buildId, transactionId:plan.work })
|
|
70
|
+
if (plan.phase !== 'prepared') throw Error('该事务需要恢复,未重新开始安装')
|
|
71
|
+
// Must fail closed when the current runtime cannot prove quiescence.
|
|
72
|
+
if (!quiesce) throw Error('当前运行模式不支持安全停服,更新已延后,旧版未改动')
|
|
73
|
+
let committed
|
|
74
|
+
try {
|
|
75
|
+
committed = await withUpdateLock(async () => {
|
|
76
|
+
await quiesce()
|
|
77
|
+
return invoke('commit',['--transaction',transactionId])
|
|
78
|
+
})
|
|
79
|
+
} catch (error) {
|
|
80
|
+
const state = JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))
|
|
81
|
+
if (['rolled-back','prepared','aborted'].includes(state.phase)) await resume?.()
|
|
82
|
+
if (state.phase === 'prepared' && error.code === 'STATE_BUSY') {
|
|
83
|
+
return { application:'deferred', error:error.message, retryable:true }
|
|
84
|
+
}
|
|
85
|
+
throw error
|
|
86
|
+
}
|
|
87
|
+
return activateCommitted(committed)
|
|
88
|
+
})().finally(() => { operation = null })
|
|
89
|
+
return operation
|
|
90
|
+
},
|
|
91
|
+
async status() {
|
|
92
|
+
let plan
|
|
93
|
+
try{plan=JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))}catch(error){if(error.code!=='ENOENT')throw error;plan={phase:'none'}}
|
|
94
|
+
if(plan.phase==='publishing'&&!operation){try{await invoke('recover');plan=JSON.parse(await readFile(path.join(home,'transaction.json'),'utf8'))}catch{/* live worker or recovery requires attention */}}
|
|
95
|
+
let writerBusy
|
|
96
|
+
try{await stat(path.join(profileDir,'package.json.lock'));writerBusy=true}catch(error){if(error.code!=='ENOENT')throw error;writerBusy=false}
|
|
97
|
+
let installedBuild
|
|
98
|
+
try{const build=await readCandidateBuild(installedRoot);installedBuild={version:build.version,buildId:build.buildId}}catch{/* incomplete package is never proof that retry is safe */}
|
|
99
|
+
return { phase: plan.phase, version: plan.version, buildId: plan.buildId, transactionId: plan.work, restartRequired: plan.phase === 'committed',
|
|
100
|
+
confirmationProtocol:1,operationActive:Boolean(operation),writerBusy,installedBuild,
|
|
101
|
+
canRetryLegacy:Boolean(installedBuild&&!operation&&!writerBusy&&['none','committed','aborted','rolled-back'].includes(plan.phase)) }
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import path from 'node:path';import {error} from './io.js';
|
|
2
2
|
import {toolWrites} from './operations.js';
|
|
3
|
-
// The shared engine returns domain data; the Host tool contract also requires
|
|
4
|
-
// the requested action on kb_flow successes and structured failures.
|
|
5
3
|
export function normalizeToolResult(name,input,value){
|
|
6
|
-
|
|
4
|
+
if(name==='kb_flow')return {...value,action:String(input?.action??'')};
|
|
5
|
+
if(name==='kb_check'&&value?.ok===false)return {execution:'error',quality:'unknown',defects:[],...value};
|
|
6
|
+
return value;
|
|
7
7
|
}
|
|
8
8
|
export function createToolRouter({kernel,engines,wb,write,online,root,kbId,sourceFromStage}){
|
|
9
9
|
return async function route({name,input,hostSession,hostAuthority,sourceStage},caller){
|
|
@@ -12,10 +12,14 @@ export function createToolRouter({kernel,engines,wb,write,online,root,kbId,sourc
|
|
|
12
12
|
if(name==='kb_bind'){if(path.resolve(a.path??'').toLowerCase()!==root.toLowerCase())throw error('BINDING_CHANGED','一个共库连接只能绑定一个库;请从库切换入口重新连接');return {ok:true,kbPath:root,kbId,initialized:true,alreadyInitialized:true,needsConfirm:false,willCreate:[],willModify:[]};}
|
|
13
13
|
if(name==='kb_init')return {ok:true,kbPath:root,kbId,alreadyInitialized:true,installState:'complete',steps:[]};
|
|
14
14
|
if(name==='kb_search'){const found=await wb({op:'search.list',mode:'body',q:a.query,retrievalMode:a.retrievalMode,limit:Math.max(1,Math.min(20,a.limit||5))});return {...found,ok:true,hits:found.items.map(h=>({...h,revision:h.revision?.slice(0,12)||null}))};}
|
|
15
|
-
if(name==='kb_check'){write(caller);return kernel.core.
|
|
15
|
+
if(name==='kb_check'){write(caller);return kernel.core.checkEntry(a);}
|
|
16
16
|
if(name==='kb_inbox'){
|
|
17
17
|
if(a.action==='list')return wb({op:'inbox.list',limit:a.limit,offset:a.offset});write(caller);
|
|
18
|
-
if(a.action==='complete')
|
|
18
|
+
if(a.action==='complete'){
|
|
19
|
+
try{return await wb({op:'inbox.complete',path:a.path,entryPath:a.entryPath});}
|
|
20
|
+
catch(e){if(['BAD_PATH','SOURCE_MISMATCH'].includes(e.code))throw error('BAD_REQUEST',e.message);throw e;}
|
|
21
|
+
}
|
|
22
|
+
throw error('BAD_REQUEST');
|
|
19
23
|
}
|
|
20
24
|
if(name==='kb_record'){
|
|
21
25
|
write(caller);if(a.action==='create'&&['知识','项目','素材','人物','画像'].includes(a.kind))return kernel.core.createEntry({...a,requestId:a.requestId??caller.operationId});
|