@kingsleyasher/dsh-knowledge-base 3.1.4 → 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/package.json CHANGED
@@ -1,78 +1,78 @@
1
- {
2
- "name": "@kingsleyasher/dsh-knowledge-base",
3
- "version": "3.1.4",
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/tree/npm/plugin-3.1.4"
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.4'
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
- const indexWritten = fresh.scanErrors.length === 0
2296
- if (indexWritten) await writeIndex(conf, fresh.entries)
2297
- else defects.push({ kind: 'index-not-written', path: '-.kbmeta/index', detail: `扫描不完整(${fresh.scanErrors.length} 处错误),已保留旧索引、未覆盖;恢复记录不删除` })
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', '扫描不完整:recover-todo 保留待下次消费')
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
- const rebuilt = await reindexLocked(conf)
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') { const result = await capture(b, { ...args, op: 'capture.complete', expectedRevision: (await userData(b)).revision }); await indexCompletedArchive(b); return { ok: true, ...result } }
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,11 +1,97 @@
1
- // npm edition: the legacy updater targets a different package and profile path.
2
- // Refuse update operations here; update this distribution via the host package manager.
3
- export function createHostUpdates({build}) {
4
- const unavailable = () => ({ok:false,code:'NPM_MANAGED_UPDATE',error:'npm 版请通过宿主插件管理器更新;内置旧包更新器已停用。'})
5
- return {
6
- async check() { return {...unavailable(),currentVersion:build.version,updateAvailable:false,installSupported:false} },
7
- async status() { return {phase:'none',installSupported:false,code:'NPM_MANAGED_UPDATE'} },
8
- async prepare() { return unavailable() },
9
- async install() { return unavailable() },
10
- }
11
- }
1
+ import { createHash } from 'node:crypto'
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { createSafeUpdate } from './safe-update.js'
6
+ import { readCandidateBuild } from './build.js'
7
+ import { compareStableVersions, readUpdateSourceBytes, startAutomaticChecks, UPDATE_INTERVAL_MS } from '../../src/host/updates.js'
8
+
9
+ const PACKAGE = '@kingsleyasher/dsh-knowledge-base'
10
+ const registry = 'https://registry.npmjs.org'
11
+ const registrySource = { id: 'npm', hosts: ['registry.npmjs.org'], file: url => url }
12
+ const packagePage = 'https://www.npmjs.com/package/' + PACKAGE
13
+ const stable = /^\d+\.\d+\.\d+$/
14
+ const sha512 = /^sha512-[A-Za-z0-9+/]{86}==$/
15
+
16
+ export function createNpmUpdateChecker({ currentVersion, fetch = globalThis.fetch, now = Date.now }) {
17
+ let cache, expiresAt = 0, pending
18
+ return {
19
+ check({ force = false } = {}) {
20
+ if (pending) return pending
21
+ if (!force && cache && now() < expiresAt) return Promise.resolve(cache)
22
+ pending = (async () => {
23
+ const base = { distribution: 'npm', currentVersion, currentChannel: 'stable', channel: 'stable', sourceName: 'npm', notesUrl: packagePage }
24
+ try {
25
+ const url = registry + '/' + encodeURIComponent(PACKAGE) + '/latest'
26
+ const raw = await readUpdateSourceBytes(fetch, registrySource, url, 1024 * 1024, 8000)
27
+ const manifest = JSON.parse(raw)
28
+ const { version, dist } = manifest
29
+ const archiveUrl = registry + '/' + PACKAGE + '/-/dsh-knowledge-base-' + version + '.tgz'
30
+ if (manifest.name !== PACKAGE || !stable.test(version) || dist?.tarball !== archiveUrl || !sha512.test(dist.integrity)) {
31
+ throw Error('npm 返回的版本或安装包信息无效')
32
+ }
33
+ const comparison = compareStableVersions(version, currentVersion)
34
+ return { ...base, ok: true, onlineChecked: true, latestVersion: version, updateAvailable: comparison > 0,
35
+ autoInstallEligible: comparison > 0, ahead: comparison < 0, integrity: dist.integrity, archiveUrl }
36
+ } catch (error) {
37
+ return { ...base, ok: false, updateAvailable: false, error: 'npm 更新检查失败:' + error.message }
38
+ }
39
+ })().then(result => {
40
+ cache = result
41
+ expiresAt = now() + (result.ok ? UPDATE_INTERVAL_MS : 5 * 60 * 1000)
42
+ return result
43
+ }).finally(() => { pending = null })
44
+ return pending
45
+ },
46
+ }
47
+ }
48
+
49
+ export function createHostUpdates({ ctx, build, profileDir, fetch = globalThis.fetch,
50
+ packageRoot = path.resolve(import.meta.dirname, '../..'), quiesce, resume, withUpdateLock }) {
51
+ const checker = createNpmUpdateChecker({ currentVersion: build.version, fetch })
52
+ const directory = ctx.get('profileContext')?.dir || profileDir
53
+ const installedRoot = directory && path.join(directory, 'node_modules', PACKAGE)
54
+ const hmr = ctx.get('hmr')
55
+ const canActivate = typeof hmr?.runExclusive === 'function' && typeof hmr?.reconcileProfile === 'function'
56
+ const safe = installedRoot && quiesce && withUpdateLock && createSafeUpdate({
57
+ profileDir: directory, packageRoot, installedRoot, journalName: '.kb-npm-updates',
58
+ quiesce, resume, withUpdateLock, activeBuild: build,
59
+ activate: canActivate ? () => hmr.runExclusive(() => hmr.reconcileProfile()) : undefined,
60
+ })
61
+ const installedHere = Boolean(installedRoot && path.relative(installedRoot, packageRoot) === '')
62
+ const supported = Boolean(safe && installedHere)
63
+ const unavailable = () => ({ ok: false, code: 'NPM_MANAGED_UPDATE',
64
+ error: '当前安装模式无法安全交接知识库,请通过 DSH 插件管理器更新 npm 版。' })
65
+ let preparing
66
+ ctx.effect(() => startAutomaticChecks(checker), 'kb-service: npm update checks')
67
+ return {
68
+ async check(body = {}) {
69
+ return { ...await checker.check({ force: body.force === true }), installSupported: supported }
70
+ },
71
+ status: () => supported ? safe.status() : { phase: 'none', installSupported: false },
72
+ install: body => supported ? safe.install(body) : unavailable(),
73
+ async prepare({ expectedVersion } = {}) {
74
+ if (!supported) return unavailable()
75
+ if (preparing) throw Error('另一个 npm 更新正在准备')
76
+ preparing = true
77
+ let temp
78
+ try {
79
+ const installed = await readCandidateBuild(installedRoot)
80
+ if (installed.version !== build.version || installed.buildId !== build.buildId) throw Error('已安装的插件发生变化,请先重启 DSH')
81
+ const release = await checker.check({ force: true })
82
+ if (!release.ok) throw Error(release.error)
83
+ if (!release.updateAvailable || release.latestVersion !== expectedVersion) throw Error('npm 最新版本已变化,请重新检查')
84
+ const raw = await readUpdateSourceBytes(fetch, registrySource, release.archiveUrl, 64 * 1024 * 1024, 20000)
85
+ if ('sha512-' + createHash('sha512').update(raw).digest('base64') !== release.integrity) throw Error('npm 安装包完整性校验失败')
86
+ temp = await mkdtemp(path.join(os.tmpdir(), 'kb-npm-update-'))
87
+ const spec = path.join(temp, 'plugin.tgz')
88
+ await writeFile(spec, raw, { flag: 'wx', mode: 0o600 })
89
+ return await safe.prepare({ spec, latestVersion: expectedVersion, currentVersion: build.version, bytes: raw.length,
90
+ sha256: createHash('sha256').update(raw).digest('hex'), integrity: release.integrity })
91
+ } finally {
92
+ preparing = false
93
+ if (temp) await rm(temp, { recursive: true, force: true }).catch(() => {})
94
+ }
95
+ },
96
+ }
97
+ }
@@ -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 }) {
12
- let operation
13
- const home = path.join(profileDir, '.kb-safe-updates')
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 + '.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, 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(path.join(profileDir,'node_modules/@local/dsh-knowledge-base'));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
- return name==='kb_flow'?{...value,action:String(input?.action??'')}:value;
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.check(a);}
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')return wb({op:'inbox.complete',path:a.path,entryPath:a.entryPath});throw error('BAD_REQUEST');
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});