dsh-requirement-dev-workbench 4.5.11 → 4.5.13

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.
Files changed (4) hide show
  1. package/CHANGELOG.md +244 -237
  2. package/dsh/index.js +334 -33
  3. package/lib/client.js +147 -27
  4. package/package.json +65 -65
package/dsh/index.js CHANGED
@@ -14,7 +14,7 @@ import { createHash } from 'node:crypto'
14
14
  import { existsSync, readFileSync } from 'node:fs'
15
15
  import { homedir, tmpdir } from 'node:os'
16
16
  import { readFile, mkdir, readdir, rm, stat, writeFile, appendFile } from 'node:fs/promises'
17
- import { dirname, join, relative, resolve, sep } from 'node:path'
17
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path'
18
18
  import { fileURLToPath } from 'node:url'
19
19
  import Schema from '@deepseek-ai/schemastery'
20
20
 
@@ -659,17 +659,21 @@ export async function findTable(config, settings, key, view = null) {
659
659
  // 没配链接、且(目录不同 或 传的是自己的模块 key)时才去模块自己的目录里找表。
660
660
  const byModuleKey = `module:${module.key}` === wanted || module.key === wanted
661
661
  if (ownDir && (byModuleKey || ownDir !== currentDir) && !module.source) {
662
- const scoped = await listTables(config, { ...settings, projectDir: ownDir }, view)
663
- if (scoped.tables.length) {
664
- // 只在「这个目录里确实有一张和这个模块对得上的表」时才换过去:
665
- // 拿别人的表顶上,会让模块静默显示别的项目的需求。
666
- const own = scoped.tables.find((table) => table.key === wanted) ??
667
- scoped.tables.find((table) => table.sourceName === wanted) ??
668
- scoped.tables.find((table) => table.tableId === wanted) ??
669
- (scoped.tables.length === 1 ? scoped.tables[0] : null)
670
- if (own) return { table: own, tables: scoped.tables, module, requirementConfig: scoped.requirementConfig, taskConfig: scoped.taskConfig }
671
- }
662
+ const scoped = await listTables(config, { ...settings, projectDir: ownDir }, view)
663
+ if (scoped.tables.length) {
664
+ // 匹配顺序:模块 key / 源名 / 表 id 都对不上时,再看这个目录是不是正好一个需求源
665
+ // (「每个项目一个需求表」是最常见的情况)。目录里有多张又对不上,就不猜 ——
666
+ // 拿别人的表顶上会让模块静默显示别的项目的需求。
667
+ const own = scoped.tables.find((table) => table.key === wanted) ??
668
+ scoped.tables.find((table) => table.sourceName === wanted) ??
669
+ scoped.tables.find((table) => table.tableId === wanted) ??
670
+ (scoped.tables.filter((table) => table.kind === 'requirement').length === 1
671
+ ? scoped.tables.find((table) => table.kind === 'requirement')
672
+ : null) ??
673
+ (scoped.tables.length === 1 ? scoped.tables[0] : null)
674
+ if (own) return { table: own, tables: scoped.tables, module, requirementConfig: scoped.requirementConfig, taskConfig: scoped.taskConfig }
672
675
  }
676
+ }
673
677
  }
674
678
  return { table: wanted ? found ?? null : tables[0] ?? null, tables, module, requirementConfig, taskConfig }
675
679
  }
@@ -679,9 +683,51 @@ const recordCache = new Map()
679
683
  let composerSession = { id: '', at: 0 }
680
684
  /** 界面自检上报的最后一帧(内存里,用于排障;不落盘、无凭证)。 */
681
685
  let uiMetrics = null
682
- const RECORD_CACHE_MS = 60_000
686
+ // 内存里存多久:切来切去、来回翻模块都吃这一份,基本不该再碰网络
687
+ const RECORD_CACHE_MS = 20 * 60_000
688
+ // 重启之后也别重拉:磁盘缓存留 7 天,只由「刷新」按钮或超过时限触发重读
689
+ const RECORD_DISK_CACHE_MS = 7 * 24 * 60 * 60_000
690
+ // 同一个 key 的读取正在跑:后来的直接等它,不再并发起第二遍 lark-cli
691
+ const inflightReads = new Map()
692
+ // 一个 base 的所有表(用来解析关联字段外键)与解析好的关联索引
693
+ const tableListCache = new Map()
694
+ const linkIndexCache = new Map()
695
+ const linkIndexInflight = new Map()
696
+ // 解析不出名字时的占位文案:这些不能当标题进索引
697
+ const PLACEHOLDER_TEXTS = new Set(['关联记录', '[关联记录]', '[附件]'])
698
+ const TABLE_LIST_CACHE_MS = 6 * 60 * 60_000
699
+ const LINK_INDEX_CACHE_MS = 30 * 60_000
683
700
 
684
701
  /** 读一张表的原始记录(60 秒内存缓存,可 fresh 强制刷新)。 */
702
+ /** 缓存键:同一张表 + 同样的读取参数才算同一次。 */
703
+ function recordCacheId(config, table, limit) {
704
+ return JSON.stringify([config.root, table.configPath, table.key, table.baseToken, table.tableId, table.viewId, table.identity, limit, table.maxRecords, table.sino && table.filter])
705
+ }
706
+
707
+ /** 磁盘缓存文件:一次读表的结果按缓存键落一个文件,重启后可复用。 */
708
+ function diskCacheFile(config, cacheId) {
709
+ const stamp = createHash('sha1').update(cacheId).digest('hex').slice(0, 20)
710
+ return join(config.root, 'cache', 'records', `${stamp}.json`)
711
+ }
712
+
713
+ async function readDiskCache(config, cacheId) {
714
+ const text = await readFile(diskCacheFile(config, cacheId), 'utf8').catch(() => null)
715
+ if (!text) return null
716
+ try {
717
+ const saved = JSON.parse(text)
718
+ if (!saved?.payload || !Array.isArray(saved.payload.records)) return null
719
+ if (Date.now() - Number(saved.at ?? 0) > RECORD_DISK_CACHE_MS) return null
720
+ return { at: Number(saved.at ?? 0), payload: saved.payload }
721
+ } catch {
722
+ return null
723
+ }
724
+ }
725
+
726
+ async function writeDiskCache(config, cacheId, entry) {
727
+ const file = diskCacheFile(config, cacheId)
728
+ await mkdir(dirname(file), { recursive: true }).catch(() => {})
729
+ await writeFile(file, JSON.stringify({ at: entry.at, payload: entry.payload }), 'utf8').catch(() => {})
730
+ }
685
731
  /**
686
732
  * lark-cli 的 `--output` 只认三个根:当前工作目录、账号临时目录、home 下的 files。
687
733
  * 写到 DSH 数据目录会被判为 "unsafe output path"(退出码 2),所以这里统一落临时目录,
@@ -761,30 +807,226 @@ async function readRecordsWithFallback({ wrapper, common, outFile, limit = 2000,
761
807
  }
762
808
  }
763
809
 
810
+ /** 表清单(一个 base 里的所有表)缓存:索引构建和「有哪些表」都不用每次问飞书。 */
811
+ async function listBaseTables(config, table) {
812
+ const key = `${table.baseToken}|${table.identity}`
813
+ const hit = tableListCache.get(key)
814
+ if (hit && Date.now() - hit.at < TABLE_LIST_CACHE_MS) return hit.tables
815
+ const larkCli = await resolveLarkCli(config.larkCli)
816
+ const wrapper = shellWrapper(larkCli)
817
+ const list = await runLark(wrapper, ['base', '+table-list', '--base-token', table.baseToken, '--as', table.identity])
818
+ const rawText = String(list.stdout || '').trim()
819
+ let parsed = []
820
+ try {
821
+ parsed = rawText ? [JSON.parse(rawText)] : []
822
+ } catch {
823
+ parsed = parseLarkRecords(rawText)
824
+ }
825
+ const collect = (node, out = []) => {
826
+ if (Array.isArray(node)) {
827
+ for (const entry of node) collect(entry, out)
828
+ return out
829
+ }
830
+ if (node && typeof node === 'object') {
831
+ if (typeof node.id === 'string' && node.id.startsWith('tbl')) out.push(node)
832
+ for (const value of Object.values(node)) collect(value, out)
833
+ }
834
+ return out
835
+ }
836
+ const tables = [...new Map(collect(parsed).map((entry) => [String(entry.id), entry])).keys()]
837
+ if (tables.length) tableListCache.set(key, { at: Date.now(), tables })
838
+ return tables
839
+ }
840
+
841
+ /** 关联索引的磁盘副本:进程重启后不用重建。 */
842
+ function linkIndexFile(config, table) {
843
+ const stamp = createHash('sha1').update(`${table.baseToken}|${table.identity}`).digest('hex').slice(0, 20)
844
+ return join(config.root, 'cache', 'link-index', `${stamp}.json`)
845
+ }
846
+
847
+ /** 先内存、再磁盘;都没有返回 null(调用方随后会后台预热)。 */
848
+ async function readLinkIndexCache(config, table) {
849
+ const key = `${table.baseToken}|${table.identity}`
850
+ const hit = linkIndexCache.get(key)
851
+ if (hit && Date.now() - hit.at < LINK_INDEX_CACHE_MS) return hit.index
852
+ const text = await readFile(linkIndexFile(config, table), 'utf8').catch(() => null)
853
+ if (!text) return null
854
+ try {
855
+ const saved = JSON.parse(text)
856
+ if (!Array.isArray(saved?.entries) || Date.now() - Number(saved.at ?? 0) > LINK_INDEX_CACHE_MS) return null
857
+ const index = new Map(saved.entries)
858
+ linkIndexCache.set(key, { at: Number(saved.at ?? 0), index })
859
+ return index
860
+ } catch {
861
+ return null
862
+ }
863
+ }
864
+
865
+ async function writeLinkIndexCache(config, table, index) {
866
+ const key = `${table.baseToken}|${table.identity}`
867
+ const at = Date.now()
868
+ linkIndexCache.set(key, { at, index })
869
+ const file = linkIndexFile(config, table)
870
+ await mkdir(dirname(file), { recursive: true }).catch(() => {})
871
+ await writeFile(file, JSON.stringify({ at, entries: [...index.entries()] }), 'utf8').catch(() => {})
872
+ }
873
+
874
+ /**
875
+ * 后台把关联索引建好,不阻塞当前这次读取;建好后把「已缓存但还没换名字」
876
+ * 的记录表重新解析一遍,下次打开就是名字。
877
+ */
878
+ function warmLinkIndex(config, table) {
879
+ const key = `${table.baseToken}|${table.identity}`
880
+ if (linkIndexInflight.has(key)) return linkIndexInflight.get(key)
881
+ const task = (async () => {
882
+ const index = await buildRecordIndex(config, table).catch(() => null)
883
+ if (index && index.size) {
884
+ await writeLinkIndexCache(config, table, index)
885
+ refreshCachedRecords(config, table, index)
886
+ }
887
+ return index
888
+ })().finally(() => linkIndexInflight.delete(key))
889
+ linkIndexInflight.set(key, task)
890
+ return task
891
+ }
892
+
893
+ /** 索引建好后,把内存里那些还没换名字的缓存直接补成名字,避免下次又显示占位。 */
894
+ function refreshCachedRecords(config, table, index) {
895
+ for (const [cacheId, entry] of recordCache) {
896
+ if (!cacheId.includes(JSON.stringify(table.baseToken))) continue
897
+ const payload = entry?.payload
898
+ if (!payload?.ok || !Array.isArray(payload.records)) continue
899
+ if (!payload.records.some((record) => hasLinkIdOnly(record))) continue
900
+ const updated = { ...payload, records: resolveLinkFields(payload.records, index), at: Date.now() }
901
+ // 只有真的换出了名字才回写;还是占位就等下一轮,别把「关联记录」写进缓存
902
+ if (updated.records.some((record) => hasLinkIdOnly(record))) continue
903
+ recordCache.set(cacheId, { at: Date.now(), payload: updated })
904
+ writeDiskCache(config, cacheId, { at: Date.now(), payload: updated }).catch(() => {})
905
+ }
906
+ }
907
+ /** 这条记录里是否还有「只有 id、没有名字」的关联字段值。 */
908
+ function hasLinkIdOnly(record) {
909
+ const fields = record?.fields && typeof record.fields === 'object' ? record.fields : record ?? {}
910
+ return Object.values(fields).some((value) => {
911
+ const list = Array.isArray(value) ? value : [value]
912
+ return list.some((item) => {
913
+ if (!item || typeof item !== 'object' || Array.isArray(item)) return false
914
+ const id = String(item.id ?? item.record_id ?? '')
915
+ if (!id.startsWith('rec')) return false
916
+ return !String(item.display_name ?? item.text ?? item.title ?? '').trim()
917
+ })
918
+ })
919
+ }
764
920
  async function fetchTableRecords(config, table, { fresh = false, limit = 2000 } = {}) {
765
- const cacheId = JSON.stringify([config.root, table.configPath, table.key, table.baseToken, table.tableId, table.viewId, table.identity, limit, table.maxRecords, table.sino && table.filter])
921
+ const cacheId = recordCacheId(config, table, limit)
766
922
  const hit = recordCache.get(cacheId)
767
923
  if (!fresh && hit && Date.now() - hit.at < RECORD_CACHE_MS) return hit.payload
924
+ // 同一张表正在读:共用这一次,别再并发重复调 lark-cli
925
+ const running = inflightReads.get(cacheId)
926
+ if (running) return running
927
+ const task = readTableRecords(config, table, { fresh, limit, cacheId }).finally(() => inflightReads.delete(cacheId))
928
+ inflightReads.set(cacheId, task)
929
+ return task
930
+ }
931
+
932
+ /** 只由 fetchTableRecords 调用(带缓存与并发合并)。 */
933
+ async function readTableRecords(config, table, { fresh, limit, cacheId }) {
934
+ if (!fresh) {
935
+ // 进程重启过也不用重拉:磁盘上那份还能用
936
+ const onDisk = await readDiskCache(config, cacheId)
937
+ if (onDisk) {
938
+ recordCache.set(cacheId, onDisk)
939
+ return onDisk.payload
940
+ }
941
+ }
768
942
  const larkCli = await resolveLarkCli(config.larkCli)
769
943
  const wrapper = shellWrapper(larkCli)
770
944
  const common = ['base', '+record-list', '--base-token', table.baseToken, '--table-id', table.tableId, '--as', table.identity]
771
945
  if (table.viewId) common.push('--view-id', table.viewId)
772
- const read = await readRecordsWithFallback({
773
- wrapper,
774
- common,
775
- outFile: larkOutputFile(table.tableId, 'records'),
776
- limit: Math.min(limit, table.maxRecords ?? limit),
777
- command: `lark-cli base +record-list --base-token ${table.baseToken} --table-id ${table.tableId} --as ${table.identity} --format ndjson`,
778
- matrixReader: (stdout) => matrixToRecords(wrapper, table, stdout),
779
- })
946
+ // 临时文件在 finally 里再清一次:读的过程中如果进程被打断(重启/崩溃),
947
+ // readRecordsWithFallback 内部的清理跑不到,临时目录就会留下 ndjson。
948
+ const outFile = larkOutputFile(table.tableId, 'records')
949
+ let read
950
+ try {
951
+ read = await readRecordsWithFallback({
952
+ wrapper,
953
+ common,
954
+ outFile,
955
+ limit: Math.min(limit, table.maxRecords ?? limit),
956
+ command: `lark-cli base +record-list --base-token ${table.baseToken} --table-id ${table.tableId} --as ${table.identity} --format ndjson`,
957
+ matrixReader: (stdout) => matrixToRecords(wrapper, table, stdout),
958
+ })
959
+ } finally {
960
+ await cleanupLarkOutput(outFile)
961
+ }
780
962
  if (read.failure) {
781
963
  return { ok: false, records: [], error: read.failure.error, detail: read.failure.detail, command: read.failure.command }
782
964
  }
783
- const payload = { ok: true, records: filterSinoRecords(read.records, table), fetchMode: read.fetchMode, warning: read.warning, ndjsonError: read.ndjsonError, at: Date.now() }
965
+ let records = filterSinoRecords(read.records, table)
966
+ // 关联字段只有 id:先用已有的索引(内存/磁盘)立刻换名字,
967
+ // 需要现建索引时**放到后台**,这次先把「关联记录」占位显示出来,不让页面干等。
968
+ if (records.some((record) => hasLinkIdOnly(record))) {
969
+ const known = await readLinkIndexCache(config, table)
970
+ if (known?.size) records = resolveLinkFields(records, known)
971
+ else warmLinkIndex(config, table)
972
+ }
973
+ const payload = { ok: true, records, fetchMode: read.fetchMode, warning: read.warning, ndjsonError: read.ndjsonError, at: Date.now() }
974
+ // 关联 id 还没解析出名字时照样缓存(先保证打开快),后台建好索引后再补一份解析后的
784
975
  recordCache.set(cacheId, { at: Date.now(), payload })
976
+ await writeDiskCache(config, cacheId, { at: Date.now(), payload })
785
977
  return payload
786
978
  }
787
979
 
980
+ /**
981
+ * 关联字段解析:飞书 record-list 的关联/查找字段只回 [{"id":"rec..."}],**不带名字**。
982
+ * 而这些 id 往往指向同一 base 里的另一张表(例如「功能名称2」→「1.模块和功能」)。
983
+ * 这里把每张表各读一次(受同一份 60 秒缓存保护),建立 record_id -> 显示值 的映射,
984
+ * 再把关联字段里的 id 换成那张表里那条记录的主标题。
985
+ */
986
+ async function buildRecordIndex(config, table) {
987
+ const candidates = (await listBaseTables(config, table)).filter(Boolean)
988
+ const index = new Map()
989
+ for (const tableId of candidates) {
990
+ const scoped = { ...table, tableId, viewId: '', sino: false, filter: null }
991
+ const payload = await fetchTableRecords(config, scoped).catch(() => null)
992
+ if (!payload?.ok) continue
993
+ for (const record of payload.records) {
994
+ const fields = record?.fields && typeof record.fields === 'object' ? record.fields : record ?? {}
995
+ const names = Object.keys(fields).filter((name) => name !== 'record_id')
996
+ // 主标题取「第一个像名字的列」:优先含 名称/页面/标题/需求 的列,其次第一列非空短文本
997
+ const named = names.find((name) => /名称|页面|标题|需求|任务|功能/.test(name) && toPlain(fields[name]))
998
+ const title = toPlain(fields[named]) || names.map((name) => toPlain(fields[name])).find((text) => text && text.length <= 80) || ''
999
+ // 「关联记录」是没解析出来的占位,不能当标题写进索引(否则会自我污染)
1000
+ if (title && !PLACEHOLDER_TEXTS.has(title)) index.set(String(record.record_id ?? record.recordId ?? ''), title)
1001
+ }
1002
+ }
1003
+ return index
1004
+ }
1005
+
1006
+ /** 把一张表记录里的关联字段 id 换成可读名字(找不到就保留「关联记录」这类占位)。 */
1007
+ export function resolveLinkFields(records, index) {
1008
+ if (!index || !index.size) return records
1009
+ const swap = (value) => {
1010
+ if (Array.isArray(value)) return value.map(swap)
1011
+ if (!value || typeof value !== 'object') return value
1012
+ const id = String(value.id ?? value.record_id ?? '')
1013
+ if (id.startsWith('rec') && index.has(id) && Object.keys(value).length <= 3) return { id, display_name: index.get(id) }
1014
+ return value
1015
+ }
1016
+ // 记录有两种形态:lark-cli 原始的扁平结构(字段直接在顶上),以及归一过的 { fields }。
1017
+ // 缓存里的记录是扁平的那种,所以两种都要能换,否则「补名字」永远不生效。
1018
+ return records.map((record) => {
1019
+ if (!record || typeof record !== 'object') return record
1020
+ if (record.fields && typeof record.fields === 'object') {
1021
+ const next = {}
1022
+ for (const [name, value] of Object.entries(record.fields)) next[name] = swap(value)
1023
+ return { ...record, fields: next }
1024
+ }
1025
+ const flat = {}
1026
+ for (const [name, value] of Object.entries(record)) flat[name] = swap(value)
1027
+ return flat
1028
+ })
1029
+ }
788
1030
  function filterSinoRecords(records, source) {
789
1031
  if (!source.sino || !source.filter || typeof source.filter !== 'object' || Array.isArray(source.filter)) return records
790
1032
  const rules = Object.entries(source.filter).filter(([, values]) => Array.isArray(values) && values.length)
@@ -1010,10 +1252,19 @@ function toPlain(value) {
1010
1252
  if (typeof value === 'number' || typeof value === 'boolean') return String(value)
1011
1253
  if (Array.isArray(value)) return value.map(toPlain).filter(Boolean).join('、')
1012
1254
  if (typeof value === 'object') {
1013
- for (const key of ['text', 'name', 'value', 'link', 'en_name']) {
1014
- if (key in value) return toPlain(value[key])
1255
+ // 关联记录 / 查找引用:lark-cli 给的是 { id, display_name }(或 { record_id, text }),
1256
+ // 以前只认 text/name,认不到就 JSON.stringify,界面于是显示成 {"id":"rec..."}。
1257
+ for (const key of ['text', 'name', 'display_name', 'displayName', 'en_name', 'value', 'link', 'title', 'record_id']) {
1258
+ if (key in value) {
1259
+ const got = toPlain(value[key])
1260
+ if (got) return got
1261
+ }
1015
1262
  }
1016
1263
  if ('file_token' in value) return '[附件]'
1264
+ // 关联记录只回了 id、没有名字(飞书 record-list 就是这样):显示可读字样,
1265
+ // 绝不把 {"id":"rec..."} 摊到界面上。
1266
+ const id = String(value.id ?? value.record_id ?? '')
1267
+ if (id.startsWith('rec')) return '关联记录'
1017
1268
  try {
1018
1269
  return JSON.stringify(value)
1019
1270
  } catch {
@@ -1645,8 +1896,8 @@ async function collectSkillsInRoot(root, items) {
1645
1896
  }
1646
1897
 
1647
1898
  /** DeepSeek Harness 通用技能根(跨项目可用);没有就返回空。 */
1648
- function harnessSkillDir() {
1649
- const dshHome = process.env.DSH_HOME
1899
+ function harnessSkillDir(settings = null) {
1900
+ const dshHome = dshHomeDir(settings)
1650
1901
  return dshHome ? join(dshHome, 'skills') : ''
1651
1902
  }
1652
1903
 
@@ -1690,7 +1941,7 @@ async function createSkill(config, settings, body) {
1690
1941
  if (!projectDir) return { ok: false, error: '还没选项目目录,先选一个再创建项目内技能' }
1691
1942
  dir = join(projectDir, '.claude', 'skills', name)
1692
1943
  } else {
1693
- const root = harnessSkillDir()
1944
+ const root = harnessSkillDir(settings)
1694
1945
  if (!root) return { ok: false, error: '取不到 DSH_HOME,定位不到 DeepSeek Harness 技能目录' }
1695
1946
  dir = join(root, name)
1696
1947
  }
@@ -1745,8 +1996,12 @@ const SKILL_CONVENTIONS = [
1745
1996
  ]
1746
1997
 
1747
1998
  /** 用户级(全局)技能目录:环境变量可以改根,和 DSH 技能管理器保持一致。 */
1999
+ /** 当前这次列表调用所属的设置(只用于环境隔离,如测试把家目录指向临时目录)。 */
2000
+ let settingsHomeDir = ''
2001
+
1748
2002
  function globalSkillDirs() {
1749
- const home = process.env.USERPROFILE || process.env.HOME || ''
2003
+ // 测试或多套 Harness 并存时,用工作台设置把「用户家目录」换掉,避免写到真机目录
2004
+ const home = process.env.USERPROFILE || process.env.HOME || settingsHomeDir || ''
1750
2005
  if (!home) return []
1751
2006
  const pick = (envName, fallback) => process.env[envName] || join(home, fallback)
1752
2007
  return [
@@ -1762,6 +2017,7 @@ function globalSkillDirs() {
1762
2017
  }
1763
2018
 
1764
2019
  function skillRootsFor(config, settings) {
2020
+ settingsHomeDir = String(settings?.homeDir ?? '')
1765
2021
  const roots = []
1766
2022
  const push = (scope, convention, label, path, note = '') => {
1767
2023
  if (!path) return
@@ -1770,7 +2026,7 @@ function skillRootsFor(config, settings) {
1770
2026
  roots.push({ scope, convention, label, path, note, exists: existsSync(path) })
1771
2027
  }
1772
2028
  // 1) DeepSeek Harness 自己的技能根:跨项目通用,也是「新建技能」默认写入的位置
1773
- const harness = harnessSkillDir()
2029
+ const harness = harnessSkillDir(settings)
1774
2030
  if (harness) push('harness', '', 'DeepSeek Harness · 通用技能', harness, 'DSH 全局技能根,任何项目都能用')
1775
2031
  // 2) 全局(用户级)约定目录
1776
2032
  for (const entry of globalSkillDirs()) push('global', entry.convention, entry.label, entry.path)
@@ -1816,7 +2072,7 @@ async function listSkills(config, settings) {
1816
2072
  items,
1817
2073
  docs,
1818
2074
  projectDir: settings.projectDir,
1819
- harnessSkillDir: harnessSkillDir(),
2075
+ harnessSkillDir: harnessSkillDir(settings),
1820
2076
  summary: Object.values(summary),
1821
2077
  }
1822
2078
  }
@@ -1838,6 +2094,26 @@ async function readSkillFile(config, settings, target) {
1838
2094
 
1839
2095
  /* -------------------------------------------- 专家 / 专家团(参考 WorkBuddy) */
1840
2096
 
2097
+ /**
2098
+ * DSH_HOME 落在哪:宿主进程通常不注入这个环境变量,但一定会注入 DSH_PROFILE_DIR
2099
+ * (用户级 profile 目录,通常就是 <DSH_HOME>/profiles/<name>)。
2100
+ * 这里按这个关系反推,避免「AI 直接创建」完稿了却写不进盘。
2101
+ */
2102
+ function dshHomeDir(settings = null) {
2103
+ const explicit = String(process.env.DSH_HOME ?? '').trim()
2104
+ if (explicit) return explicit
2105
+ const profileDir = String(process.env.DSH_PROFILE_DIR ?? '').trim()
2106
+ if (profileDir) {
2107
+ const parent = dirname(profileDir)
2108
+ if (basename(parent) === 'profiles') return dirname(parent)
2109
+ }
2110
+ // 工作台设置里的 dshHome 优先(测试、或多套 Harness 并存时靠它指路)
2111
+ const configured = String(settings?.dshHome ?? '').trim()
2112
+ if (configured) return configured
2113
+ const home = String(process.env.USERPROFILE || process.env.HOME || settingsHomeDir || '').trim()
2114
+ return home ? join(home, '.dsh') : ''
2115
+ }
2116
+
1841
2117
  /** 专家文件放哪:通用 = DSH_HOME/agents;项目 = <项目>/<约定>/agents(默认 .claude)。 */
1842
2118
  function expertDirFor(scope, convention, settings) {
1843
2119
  if (scope === 'project') {
@@ -1846,7 +2122,8 @@ function expertDirFor(scope, convention, settings) {
1846
2122
  const safe = SKILL_CONVENTIONS.some((entry) => entry.dir && entry.dir === convention) ? convention : '.claude'
1847
2123
  return join(projectDir, safe, 'agents')
1848
2124
  }
1849
- return process.env.DSH_HOME ? join(process.env.DSH_HOME, 'agents') : ''
2125
+ const home = dshHomeDir(settings)
2126
+ return home ? join(home, 'agents') : ''
1850
2127
  }
1851
2128
 
1852
2129
  function expertTargets(config, settings) {
@@ -1860,7 +2137,8 @@ function expertTargets(config, settings) {
1860
2137
  function teamFiles(config, settings) {
1861
2138
  const projectDir = String(settings.projectDir ?? '').trim()
1862
2139
  const list = []
1863
- if (process.env.DSH_HOME) list.push({ scope: 'harness', path: join(process.env.DSH_HOME, 'experts', 'teams.json'), label: 'DeepSeek Harness 通用专家团' })
2140
+ const dshHome = dshHomeDir(settings)
2141
+ if (dshHome) list.push({ scope: 'harness', path: join(dshHome, 'experts', 'teams.json'), label: 'DeepSeek Harness 通用专家团' })
1864
2142
  if (projectDir) list.push({ scope: 'project', path: join(projectDir, '.dsh', 'experts', 'teams.json'), label: '当前项目专家团' })
1865
2143
  return list
1866
2144
  }
@@ -1962,6 +2240,12 @@ async function createExpert(config, settings, body) {
1962
2240
  const scope = body?.scope === 'project' ? 'project' : 'harness'
1963
2241
  const dir = expertDirFor(scope, String(body?.convention || '.claude'), settings)
1964
2242
  if (!dir) return { ok: false, error: scope === 'project' ? '还没选项目目录,选一个再创建项目专家' : '取不到 DSH_HOME,定位不到通用专家目录' }
2243
+ // 兜底:通用专家写进 <DSH_HOME>/agents,但工作台是从「同级 skills 目录」反推专家目录的。
2244
+ // DSH_HOME 下没有 skills 时,写完会扫不到、界面看着像「没创建」——这里顺手建一个空目录。
2245
+ if (scope === 'harness') {
2246
+ const skillsDir = join(dirname(dir), 'skills')
2247
+ if (!existsSync(skillsDir)) await mkdir(skillsDir, { recursive: true }).catch(() => {})
2248
+ }
1965
2249
  const convention = scope === 'project' ? String(body?.convention || '.claude') : ''
1966
2250
  const file = join(dir, `${id}.md`)
1967
2251
  if (existsSync(file) && !body?.overwrite) return { ok: false, error: `专家「${id}」已存在,换个标识或先删掉它`, path: file, exists: true }
@@ -3265,7 +3549,24 @@ export function apply(ctx, config) {
3265
3549
  // 只改这一个模块自己的项目目录;全局项目设置一格都不动。
3266
3550
  const patch = view.modules.map((item, position) => (position === index ? { ...item, projectDir: raw } : { ...item }))
3267
3551
  const saved = await writeView(config, { modules: patch })
3268
- return sendJson(res, 200, { ok: true, moduleKey, projectDir: raw || String(settings.projectDir ?? ''), view: saved })
3552
+ // v4.5.12 修:以前写成功也返回 { ok, moduleKey, projectDir, view },**没有 ownProjectDir**,
3553
+ // 和 GET /workspace 的结构不一致。前端拿到后就当成「这个模块没有自己的目录」,
3554
+ // 于是一路退回全局 settings.projectDir —— 表现成「改一个模块,另一个也跟着变」。
3555
+ // 现在 POST 也回同一份扁平结构(own/inherited/...),前端两边能用同一套字段。
3556
+ const savedModule = saved.modules[index] ?? { ...view.modules[index], projectDir: raw }
3557
+ const effective = moduleProjectDir(settings, savedModule)
3558
+ return sendJson(res, 200, {
3559
+ ok: true,
3560
+ moduleKey,
3561
+ found: true,
3562
+ projectDir: effective,
3563
+ ownProjectDir: String(savedModule?.projectDir ?? ''),
3564
+ inherited: !String(savedModule?.projectDir ?? '').trim(),
3565
+ hasSource: Boolean(await sourceHasTable(effective, { ...view, modules: patch })),
3566
+ tableCount: (await listTables(config, { ...settings, projectDir: effective }, { ...view, modules: patch })).tables.length,
3567
+ moduleSource: (() => { const tb = moduleTable(savedModule, { identity: config.identity }); return tb ? { tableId: tb.tableId, baseToken: tb.baseToken, label: tb.label, identity: tb.identity, readOnly: tb.readOnly } : null })(),
3568
+ view: saved,
3569
+ })
3269
3570
  }
3270
3571
 
3271
3572
  // 模块级数据源:每个模块自己记一个链接(存 view.json 的模块上),改了只影响这一个模块。