dsh-agent-soul 0.1.0 → 0.2.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/index.js CHANGED
@@ -42,7 +42,7 @@ import { purposeState, savePurposeState } from './store.js'
42
42
  import { satisfyDrives, summarize, openGoals, renderPurpose } from './purpose.js'
43
43
  import { observeAgent, unobserveAll, normalizeMoodConfig } from './mood.js'
44
44
  import { registerMemoryTool, registerGoalTool, setFallbackCwd } from './tool.js'
45
- import { registerApi } from './api.js'
45
+ import { registerApi, registerAssets } from './api.js'
46
46
 
47
47
  /** 插件名 = 裸包名,必须与 package.json 的 name、cordis.patch.yml 的 name、插件目录名三者一致。 */
48
48
  export const name = 'dsh-agent-soul'
@@ -54,6 +54,53 @@ const MAINTAIN_INTERVAL_MS = 10 * 60 * 1000
54
54
 
55
55
  let lastMaintainAt = 0
56
56
 
57
+ /** 诊断计数:只用来回答「text() 到底被调了几次」,不参与任何业务逻辑。 */
58
+ let diagCount = 0
59
+
60
+ /**
61
+ * 诊断探针(2026-10-29 加,排查「记忆/目的始终为空」)。
62
+ *
63
+ * 为什么必须加这个:提取链路的每一步失败都是**静默**的 ——
64
+ * agent 为空、范围查询拿不到事件、sessionId 每轮都变,三种情况的外部表现完全一样
65
+ * (记忆卡不出现、日志没有任何报错)。不加探针只能靠猜。
66
+ * 这里只写日志、不改任何逻辑,定位完可以整段删掉。
67
+ */
68
+ function diag(agent, extra = '') {
69
+ diagCount += 1
70
+ const session = agent?.session
71
+ if (session === undefined || session === null) {
72
+ note('diag', `#${diagCount} text() 被调用,但 context.agent 为空 ${extra}`)
73
+ return
74
+ }
75
+ const id = String(session?.header?.id ?? session?.id ?? '')
76
+ const seq = typeof session.seq === 'number' ? session.seq : 'NA'
77
+ const first = typeof session.firstLiveSeq === 'number' ? session.firstLiveSeq : 'NA'
78
+ const hasSnap = typeof session.snapshotEvents === 'function'
79
+ let all = -1
80
+ let owner = -1
81
+ let kinds = ''
82
+ let err = ''
83
+ try {
84
+ const list = session.snapshotEvents() || []
85
+ all = list.length
86
+ owner = list.filter((e) => e?.type === 'user/message').length
87
+ // 看一眼真实事件的字段名:万一是 kind 而不是 type,提取会整条落空
88
+ const sample = list.filter((e) => (e?.type ?? e?.kind) === 'user/message').slice(-1)[0]
89
+ kinds = sample === undefined ? '无用户消息' : `type=${String(sample.type)} kind=${String(sample.kind)}`
90
+ } catch (e) {
91
+ err = e instanceof Error ? e.message : String(e)
92
+ }
93
+ let ranged = -1
94
+ try {
95
+ const to = typeof session.seq === 'number' ? session.seq + 1 : undefined
96
+ const list2 = to === undefined ? session.snapshotEvents(0) : session.snapshotEvents(0, to)
97
+ ranged = Array.isArray(list2) ? list2.length : -2
98
+ } catch (e) {
99
+ ranged = -3
100
+ }
101
+ note('diag', `#${diagCount} sess=${id.slice(0, 8) || '空'} seq=${seq} first=${first} 快照函数=${hasSnap} 全量=${all}(用户消息 ${owner}) 范围查询=${ranged} ${kinds} ${extra} err=${err || '无'}`)
102
+ }
103
+
57
104
  /** 注入时的轻量维护:衰减/压缩按自己的节奏,提取每回合都做(增量,很便宜)。 */
58
105
  function tick(agent, cwd, config, { allowMaintain = true } = {}) {
59
106
  const now = Date.now()
@@ -69,9 +116,15 @@ function tick(agent, cwd, config, { allowMaintain = true } = {}) {
69
116
  }
70
117
  }
71
118
 
72
- if (agent === undefined || agent === null) return
119
+ if (agent === undefined || agent === null) {
120
+ diag(agent, '【tick 在此返回,记忆提取根本没跑】')
121
+ return
122
+ }
73
123
  try {
74
- const { candidates } = collectCandidates(agent, { limit: config.maxPerTick ?? 12 })
124
+ const result = collectCandidates(agent, { limit: config.maxPerTick ?? 12 })
125
+ const { candidates } = result
126
+ // 诊断:把「扫到几个事件 / 游标在哪 / 候选几个」写进日志
127
+ diag(agent, `scanned=${result.scanned} from=${result.from} to=${result.to} 候选=${candidates.length}`)
75
128
  if (candidates.length === 0) return
76
129
  // 自动记进**项目卡**(有 cwd 时),否则全局卡:跟随当前工作上下文,避免跨项目污染
77
130
  const useProject = String(cwd ?? '').trim() !== '' && config.projectMemoryEnabled !== false
@@ -97,6 +150,13 @@ export function apply(ctx) {
97
150
  note('api', `注册失败:${error instanceof Error ? error.message : error}`)
98
151
  }
99
152
 
153
+ try {
154
+ registerAssets(ctx)
155
+ } catch (error) {
156
+ // 表情图挂了也只是设置页缺图,不影响心情记账
157
+ note('api', `表情图注册失败:${error instanceof Error ? error.message : error}`)
158
+ }
159
+
100
160
  registerMemoryTool(ctx)
101
161
  registerGoalTool(ctx)
102
162
 
package/lib/memory.js CHANGED
@@ -523,7 +523,9 @@ export function compactCard(card, config = {}, { targetRatio = 0.85, now = Date.
523
523
  const targetChars = Math.max(600, Math.floor(budget * clamp(targetRatio, 0.3, 0.95)))
524
524
  let steps = 0
525
525
 
526
- while (steps < 5000) {
526
+ // 上限 500:正常一张卡几百条,几十次就收敛。留这个护栏是防 stepDown 被改坏后
527
+ // 单向不收敛,在注入路径里把一个回合卡成死循环;500 足够覆盖极端容量。
528
+ while (steps < 500) {
527
529
  const chars = renderCard(card, { config: cfg, now, full: true }).length
528
530
  if (chars <= targetChars) break
529
531
  const candidates = card.records.filter((record) => record.pinned !== true
package/lib/mood.js CHANGED
@@ -75,6 +75,10 @@ const MACHINE_PREFIXES = ['subagent', 'goal', 'tool-', 'system-', 'schedule']
75
75
 
76
76
  const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n))
77
77
 
78
+ /** 转义正则元字符:symbol 化的词表是动态拼进 new RegExp 的,
79
+ * 万一将来有人往 VERBS 里加 `*`/`.`/`?` 等会静默改判 —— 先逃掉就不踩这个坑。 */
80
+ const escapeRegExp = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
81
+
78
82
  /** 七情取整(状态里存小数,只有对外显示取整)。 */
79
83
  export const displayDims = (s) => Object.fromEntries(DIMS.map(([k]) => [k, Math.round(s.dims[k] || 0)]))
80
84
 
@@ -87,13 +91,21 @@ export function moodLabel(v) {
87
91
  return '难过'
88
92
  }
89
93
 
90
- export function moodEmoji(v) {
91
- const n = Math.round(Number(v) || 0)
92
- if (n >= 80) return '😊'
93
- if (n >= 62) return '🙂'
94
- if (n >= 42) return '😌'
95
- if (n >= 25) return '🥺'
96
- return '😢'
94
+ /**
95
+ * 五档表情对应哪张图(assets/face-<名字>.png)。
96
+ * 图是跟着心情走的同一套(原 dsh-feiyu-mood 那五张),阈值也跟它一致:
97
+ * 80 以上欢喜、62 以上开心、42 以上一般、25 以上心疼,再低就是难过。
98
+ * 返回文件名里的那段名字,Web 端拼成图地址 —— 这里不掺 URL,lib 层只算账。
99
+ */
100
+ export function moodFace(v) {
101
+ const n = Number(v)
102
+ // 认不出数值时按中间那档走(原 dsh-feiyu-mood 也是这么兜的),别让页面开天窗
103
+ if (!Number.isFinite(n)) return 'ok'
104
+ if (n >= 80) return 'great'
105
+ if (n >= 62) return 'good'
106
+ if (n >= 42) return 'ok'
107
+ if (n >= 25) return 'worry'
108
+ return 'sad'
97
109
  }
98
110
 
99
111
  /** 最高的几根七情(≥15 才算数)。 */
@@ -135,6 +147,7 @@ export function normReason(s, owner = '') {
135
147
  const raw = String(s || '')
136
148
  if (!name || !raw) return raw
137
149
  const speechVerbs = '说|问|讲|答|喊|回|笑|想|觉得|解释|抱怨|嘟囔|念叨'
150
+ .split('|').map(escapeRegExp).join('|')
138
151
  const sentences = raw.split(/(?<=[。!?!?;;])/)
139
152
  return sentences.map((sent) => {
140
153
  const pronounCount = (sent.match(/[她他]/g) || []).length
@@ -510,8 +523,9 @@ export function sessionModelOf(agent) {
510
523
  * @param reply 她这轮说的话
511
524
  * @param mode '' | 'work' | 'talk'
512
525
  * @param o { self, owner, aliases, judgeProvider, judgeModel }
526
+ * @param note 可选的日志函数(纯逻辑模块不 import env,由调用方注入)
513
527
  */
514
- export async function judgeMood(llm, agent, userText, reply, mode, o) {
528
+ export async function judgeMood(llm, agent, userText, reply, mode, o, note) {
515
529
  if (!llm || typeof llm.stream !== 'function') return null
516
530
  const picked = (o.judgeProvider && o.judgeModel) ? { provider: o.judgeProvider, model: o.judgeModel } : null
517
531
  const target = picked || sessionModelOf(agent)
@@ -561,7 +575,9 @@ export async function judgeMood(llm, agent, userText, reply, mode, o) {
561
575
  if (chunk.type === 'text-delta') out += chunk.text
562
576
  if (chunk.type === 'finish' && chunk.reason && chunk.reason.kind === 'error') return null
563
577
  }
564
- } catch {
578
+ } catch (e) {
579
+ // 静默失败会让「心情停住不动」毫无线索:至少留一行日志,诊断时不至于全靠猜
580
+ if (note) note('mood', `判断调用失败:${e instanceof Error ? e.message : String(e)}`)
565
581
  return null
566
582
  }
567
583
  return parseDelta(out, o.owner)
@@ -625,7 +641,7 @@ export function observeAgent(agent, { llm, config, note }) {
625
641
  const mode = EXTERNAL_TRIGGER.has(kind) ? 'work' : (SELF_SPEAK.has(kind) ? 'talk' : '')
626
642
  judgeChain = judgeChain
627
643
  .then(async () => {
628
- const delta = await judgeMood(llm, agent, info.text, reply, mode, names())
644
+ const delta = await judgeMood(llm, agent, info.text, reply, mode, names(), note)
629
645
  if (!delta) return
630
646
  const anyDim = DIMS.some(([k]) => delta.dims[k] !== 0)
631
647
  const step = Math.round(delta.moodDelta / MOOD_STEP_DIVISOR)
package/lib/paths.js CHANGED
@@ -18,7 +18,7 @@
18
18
  * 他已经写好了 AGENT.md 和项目人格。换插件不该逼他搬家 ——
19
19
  * 路径一致意味着装上就能用,卸载也不丢东西。
20
20
  */
21
- import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
21
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, copyFileSync } from 'node:fs'
22
22
  import { homedir } from 'node:os'
23
23
  import { join, resolve } from 'node:path'
24
24
 
@@ -137,9 +137,10 @@ export function atomicWrite(file, text) {
137
137
  try {
138
138
  renameSync(tmp, file)
139
139
  } catch {
140
- // Windows 上目标被占用时 rename 会失败:退化成直接覆盖(至少不丢内容)
140
+ // Windows 上目标被占用时 rename 会失败:退化成系统级拷贝覆盖(cp 不在 JS 堆里
141
+ // 走一遍全量缓冲),至少不丢内容;记忆卡可达 MB 级,别再 readFileSync 读进内存。
141
142
  try {
142
- writeFileSync(file, readFileSync(tmp, 'utf8'), 'utf8')
143
+ copyFileSync(tmp, file)
143
144
  unlinkSync(tmp)
144
145
  } catch {
145
146
  /* 都失败了就算了,调用方会在下次写入时再试 */
package/lib/registry.js CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  readText,
28
28
  slugFor,
29
29
  } from './paths.js'
30
+ import { note } from './env.js'
30
31
 
31
32
  /** 登记表位置(与 dsh-agent-md 同一个文件)。 */
32
33
  export function registryPath() {
@@ -58,6 +59,13 @@ export function registerProject(cwd, patch = {}) {
58
59
  const registry = readRegistry()
59
60
  const { slug, personaPath: path } = slugFor(cwd)
60
61
  const now = new Date().toISOString()
62
+ // 32-bit FNV-1a slug 的碰撞检测:算法为兼容 dsh-agent-md 不能改(换算法=换命名空间),
63
+ // 只能在这里盯住 —— 不同 cwd 算出同 slug 会共用同一份人格/记忆文件,需人工处理。
64
+ // 概率极低(几百个工作区里 32bit 足够稀疏),但撞了就静默丢文件,不值得赌。
65
+ const collided = registry.projects.find((p) => p !== null && typeof p === 'object' && p.key !== key && p.slug === slug)
66
+ if (collided !== undefined) {
67
+ note('persona', `⚠️ slug 碰撞:${cwd} 与 ${collided.cwd} 都算出 ${slug}(共享同一份人格/记忆文件)`)
68
+ }
61
69
  const existing = registry.projects.find((p) => p !== null && typeof p === 'object' && p.key === key)
62
70
  if (existing !== undefined) {
63
71
  existing.cwd = cwd
package/lib/store.js CHANGED
@@ -52,6 +52,8 @@ import {
52
52
  const cardCache = new Map()
53
53
  const moodCache = new Map()
54
54
  let purposeCache = null
55
+ /** 配置缓存带 mtime:用户可能直接用编辑器改 persona.json(README 明确说可以),
56
+ * 只在内存里缓存会让外部改动永不生效。跟记忆卡同一套「mtime 失效」模式。 */
55
57
  let configCache = null
56
58
 
57
59
  /** 配置文件路径(为了不破坏 dsh-agent-md,用另一个文件名)。 */
@@ -255,22 +257,27 @@ export const DEFAULT_CONFIG = Object.freeze({
255
257
  })
256
258
 
257
259
  export function loadConfig() {
258
- if (configCache !== null) return configCache
260
+ const file = CONFIG_FILE()
261
+ const stamp = mtimeOf(file)
262
+ if (configCache !== null && configCache.stamp === stamp) return configCache.value
259
263
  let raw = {}
260
264
  try {
261
- const text = readText(CONFIG_FILE())
265
+ const text = readText(file)
262
266
  raw = text === '' ? {} : JSON.parse(text)
263
267
  } catch {
264
268
  raw = {}
265
269
  }
266
- configCache = { ...DEFAULT_CONFIG, ...(raw !== null && typeof raw === 'object' ? raw : {}) }
267
- return configCache
270
+ const value = { ...DEFAULT_CONFIG, ...(raw !== null && typeof raw === 'object' ? raw : {}) }
271
+ configCache = { stamp, value }
272
+ return value
268
273
  }
269
274
 
270
275
  export function saveConfig(patch) {
271
- configCache = { ...loadConfig(), ...(patch ?? {}) }
272
- atomicWrite(CONFIG_FILE(), `${JSON.stringify(configCache, null, 2)}\n`)
273
- return configCache
276
+ const value = { ...loadConfig(), ...(patch ?? {}) }
277
+ atomicWrite(CONFIG_FILE(), `${JSON.stringify(value, null, 2)}\n`)
278
+ // 写盘后立刻失效缓存:下一轮 loadConfig 会按新 mtime 重读,保证进程内一致
279
+ configCache = { stamp: mtimeOf(CONFIG_FILE()), value }
280
+ return value
274
281
  }
275
282
 
276
283
  /** 测试用:丢掉所有缓存。 */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agent-soul",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "给 DSH 的 agent 一套会忘事的记忆、一份会变的人格和一份会起伏的心情:人格按小节合并(项目覆盖全局但不吃掉全局),记忆按人的规律衰减(清晰→模糊→只剩印象→遗忘),「心里惦记的事」让她的主动有连续性,心情跟着每轮对话自己判断、自己平复(不注入、无挂饰)。",
6
6
  "keywords": [
@@ -24,6 +24,7 @@
24
24
  },
25
25
  "files": [
26
26
  "lib",
27
+ "assets",
27
28
  "docs",
28
29
  "tools",
29
30
  "cordis.patch.yml",
@@ -31,15 +32,16 @@
31
32
  "LICENSE"
32
33
  ],
33
34
  "scripts": {
34
- "test": "node tests/memory.test.js && node tests/mood.test.js && node tests/persona.test.js && node tests/purpose.test.js && node tests/registry.test.js && node tests/smoke.test.js && node tests/client.test.js",
35
+ "build:client": "node tools/build-client.mjs",
36
+ "test": "node tools/build-client.mjs && node tests/memory.test.js && node tests/mood.test.js && node tests/persona.test.js && node tests/purpose.test.js && node tests/registry.test.js && node tests/smoke.test.js && node tests/client.test.js",
35
37
  "test:memory": "node tests/memory.test.js",
36
38
  "test:mood": "node tests/mood.test.js",
37
39
  "test:persona": "node tests/persona.test.js",
38
40
  "test:purpose": "node tests/purpose.test.js",
39
41
  "test:registry": "node tests/registry.test.js",
40
42
  "test:smoke": "node tests/smoke.test.js",
41
- "test:client": "node tests/client.test.js",
42
- "sync": "node tools/sync.mjs"
43
+ "test:client": "node tools/build-client.mjs && node tests/client.test.js",
44
+ "sync": "node tools/build-client.mjs"
43
45
  },
44
46
  "peerDependencies": {
45
47
  "@deepseek-ai/cordis": "^4.0.1"
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * build-client.mjs —— 把 lib/client/ 下的浏览器端片段拼成 DSH 需要的单包 bundle
4
+ * (lib/client.js)。
5
+ *
6
+ * 为什么需要它:
7
+ * DSH 客户端模块系统「一个包只出一个 bundle,兄弟文件无法同步 require」
8
+ * (dsh-switchman/client.js 顶部的注释明说)。所以要么挤成单个 1200+ 行的文件,
9
+ * 要么用一个零依赖的拼接脚本,把按职责拆开的片段合成一个入口。这里选后者。
10
+ *
11
+ * 已解决原单文件的维护痛点:
12
+ * 每个 Tab、样式、API、共享组件各归一个片段文件,能单独阅读、单独 node --check。
13
+ *
14
+ * 拼接规则:
15
+ * · 片段是「工厂函数作用域内」的纯 var/function 声明,不 import/export 任何东西
16
+ * (ESM 关键字会让 concat 后的作用域乱掉);
17
+ * · 顺序即依赖顺序:靠前的片段声明的函数/变量,靠后的片段可以引用;
18
+ * · 唯一外壳(window.__ModuleLoader__.load 包装 + React/hooks/NS)写死在本脚本;
19
+ * · 每个片段都能 node --check 过 —— 引用未定义变量只是运行时 ReferenceError,
20
+ * node --check 只查语法,不会拦。
21
+ *
22
+ * 运行:node tools/build-client.mjs (也挂在 npm run sync / test 前面)
23
+ */
24
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
25
+ import { dirname, join } from 'node:path'
26
+ import { fileURLToPath } from 'node:url'
27
+
28
+ const here = dirname(fileURLToPath(import.meta.url))
29
+ const projectRoot = join(here, '..')
30
+ const clientDir = join(projectRoot, 'lib', 'client')
31
+ const outFile = join(projectRoot, 'lib', 'client.js')
32
+
33
+ // 拼接顺序 = 依赖顺序。改了顺序要同步更新这个数组。
34
+ const ORDER = [
35
+ 'styles.js', // CSS + ensureStyles(不依赖 h,最先)
36
+ 'api.js', // API 常量 + readJson/apiGet/apiPost/cwdOf/timeLabel
37
+ 'components.js', // 共享小组件 + 标签常量(依赖 h)
38
+ 'overview-tab.js',
39
+ 'persona-tab.js',
40
+ 'memory-tab.js',
41
+ 'purpose-tab.js',
42
+ 'mood-tab.js',
43
+ 'settings-tab.js',
44
+ 'app.js', // SoulSection + ErrorBoundary + apply + module.exports
45
+ ]
46
+
47
+ const DOC = `/**
48
+ * client.js —— 浏览器半侧:设置页(手写 __ModuleLoader__ bundle)。
49
+ *
50
+ * ⚠️ 本文件是【生成物】,不要直接改 —— 改 lib/client/*.js 然后跑
51
+ * \`node tools/build-client.mjs\`(或 \`npm run sync\`)。DSH 客户端每个包只
52
+ * 出一个 bundle、兄弟文件无法同步 require,所以把按职责拆开的片段拼回单文件。
53
+ */
54
+
55
+ `
56
+
57
+ const HEADER =
58
+ DOC +
59
+ `window.__ModuleLoader__.load({
60
+ id: 'dsh-agent-soul',
61
+ factory: function (require) {
62
+ // ⚠️ 这两行不能省:宿主只提供 require,不提供 CommonJS 的 module/exports。
63
+ // 少了它们,factory 里一碰 module.exports 就是 "module is not defined",
64
+ // 而 DSH 的启动日志只会说「1 entry did not activate」—— 整个应用起不来。
65
+ // node --check 查不出这个问题:它是语法层面合法的,只有真跑一次才炸。
66
+ var module = { exports: {} }
67
+ var exports = module.exports
68
+
69
+ var React = require('react')
70
+ var h = React.createElement
71
+ var useCallback = React.useCallback
72
+ var useEffect = React.useEffect
73
+ var useState = React.useState
74
+
75
+ var NS = 'dsh-agent-soul'
76
+ `
77
+
78
+ const FOOTER = `
79
+ return module.exports
80
+ }
81
+ })
82
+ `
83
+
84
+ const missing = ORDER.filter((file) => !existsSync(join(clientDir, file)))
85
+ if (missing.length > 0) {
86
+ console.error(`缺少片段:\n ${missing.map((f) => join(clientDir, f)).join('\n ')}`)
87
+ process.exit(1)
88
+ }
89
+
90
+ const fragments = ORDER.map((file) => readFileSync(join(clientDir, file), 'utf8'))
91
+ const bundle = HEADER + '\n' + fragments.join('\n\n') + FOOTER
92
+ writeFileSync(outFile, bundle, 'utf8')
93
+ console.log(`已拼接 ${outFile}(${ORDER.length} 个片段,${bundle.split('\n').length} 行)`)
package/tools/sync.mjs DELETED
@@ -1,130 +0,0 @@
1
- /**
2
- * sync.mjs —— 把源码同步到 DSH 插件目录(原子写,不会读到半截文件)。
3
- *
4
- * ── 为什么需要它 ──
5
- * 2026-10-28 真事故:用 `cp` 覆盖 client.js 时,DSH 正好在启动读取它,
6
- * 读到了写了一半的文件,日志里只有一句
7
- *
8
- * web boot: 1 entry did not activate
9
- * dsh-agent-soul: bundle script ... failed to load
10
- *
11
- * 整个桌面应用起不来。代码本身没问题,纯粹是复制和读取撞在了一起。
12
- *
13
- * 所以这里改成了「先写 .tmp,再 rename」:同一分区上 rename 是原子的,
14
- * 读的人要么看到旧版、要么看到新版,不会看到半截。
15
- *
16
- * ── 用法 ──
17
- * node tools/sync.mjs 同步到 <DSH_HOME>/plugins/dsh-agent-soul
18
- * node tools/sync.mjs --to <目录> 指定目标
19
- * node tools/sync.mjs --dry 只看会改什么,不真写
20
- */
21
- import { copyFileSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs'
22
- import { homedir } from 'node:os'
23
- import { dirname, join, resolve } from 'node:path'
24
- import { fileURLToPath } from 'node:url'
25
-
26
- const SRC = resolve(dirname(fileURLToPath(import.meta.url)), '..')
27
- const argv = process.argv.slice(2)
28
- const dry = argv.includes('--dry')
29
- const toIndex = argv.indexOf('--to')
30
- const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
31
- const DEST = toIndex >= 0 && argv[toIndex + 1] ? resolve(argv[toIndex + 1]) : join(dshHome, 'plugins', 'dsh-agent-soul')
32
-
33
- /** 同步的项:目录整份同步,文件单个同步。 */
34
- const DIRS = ['lib', 'tests', 'docs']
35
- const FILES = ['package.json', 'cordis.patch.yml', 'README.md', 'LICENSE']
36
-
37
- /**
38
- * 原子复制:先落到同目录的 .tmp-<pid>,再 rename 覆盖。
39
- * rename 在同一分区是原子操作,读的人不会看到半截内容。
40
- */
41
- function atomicCopy(from, to) {
42
- const tmp = `${to}.tmp-${process.pid}`
43
- copyFileSync(from, tmp)
44
- renameSync(tmp, to)
45
- }
46
-
47
- function syncDir(name) {
48
- const from = join(SRC, name)
49
- if (!existsSync(from)) return { added: 0, updated: 0 }
50
- const to = join(DEST, name)
51
- if (!dry) mkdirSync(to, { recursive: true })
52
-
53
- let added = 0
54
- let updated = 0
55
- for (const entry of readdirSync(from)) {
56
- const srcFile = join(from, entry)
57
- if (!statSync(srcFile).isFile()) continue
58
- const dstFile = join(to, entry)
59
- const existed = existsSync(dstFile)
60
- if (!dry) atomicCopy(srcFile, dstFile)
61
- if (existed) updated += 1
62
- else added += 1
63
- }
64
- return { added, updated }
65
- }
66
-
67
- function syncFile(name) {
68
- const from = join(SRC, name)
69
- if (!existsSync(from)) return null
70
- const dstFile = join(DEST, name)
71
- const existed = existsSync(dstFile)
72
- if (!dry) atomicCopy(from, dstFile)
73
- return { added: existed ? 0 : 1, updated: existed ? 1 : 0 }
74
- }
75
-
76
- // ---- 主流程 ----
77
-
78
- if (!existsSync(DEST) && !dry) {
79
- console.error(`目标目录不存在:${DEST}`)
80
- console.error('第一次安装请先手动建目录并在 profile 里登记,参考 README「安装」。')
81
- process.exit(1)
82
- }
83
-
84
- console.log(`源:${SRC}`)
85
- console.log(`目标:${DEST}${dry ? '(--dry,只看不改)' : ''}`)
86
- console.log('')
87
-
88
- let added = 0
89
- let updated = 0
90
- for (const dir of DIRS) {
91
- const result = syncDir(dir)
92
- added += result.added
93
- updated += result.updated
94
- if (result.added + result.updated > 0) {
95
- console.log(` ${dir}/ 新增 ${result.added},更新 ${result.updated}`)
96
- }
97
- }
98
- for (const file of FILES) {
99
- const result = syncFile(file)
100
- if (result === null) {
101
- console.log(` ${file} 源码里没有,跳过`)
102
- continue
103
- }
104
- added += result.added
105
- updated += result.updated
106
- }
107
-
108
- // 清理上次中断留下的 .tmp(只清自己这套命名)
109
- try {
110
- for (const dir of DIRS) {
111
- const target = join(DEST, dir)
112
- if (!existsSync(target)) continue
113
- for (const entry of readdirSync(target)) {
114
- if (/\.tmp-\d+$/.test(entry)) {
115
- rmSync(join(target, entry), { force: true })
116
- console.log(` 清掉残留临时文件 ${dir}/${entry}`)
117
- }
118
- }
119
- }
120
- } catch {
121
- /* 清理失败不影响同步结果 */
122
- }
123
-
124
- console.log('')
125
- console.log(dry ? '(dry run 结束,什么都没改)' : `同步完成:新增 ${added},更新 ${updated} 个文件`)
126
- if (!dry) {
127
- console.log('')
128
- console.log('⚠️ 改动要重启 DSH(或刷新页面加载 client.js)才生效。')
129
- console.log(' 重启前确认没有正在进行的同步 —— 这个脚本已经是原子写,不会再读到半截文件。')
130
- }