dsh-macro-memory 0.0.0-stage → 0.3.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.
Files changed (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +457 -2
  3. package/cordis.patch.yml +6 -0
  4. package/lib/client.js +3623 -0
  5. package/lib/index.js +469 -0
  6. package/lib/macro/brand.js +82 -0
  7. package/lib/macro/bridge.js +158 -0
  8. package/lib/macro/chain.js +206 -0
  9. package/lib/macro/contract.js +471 -0
  10. package/lib/macro/cost.js +164 -0
  11. package/lib/macro/defs/admin.js +439 -0
  12. package/lib/macro/defs/dream.js +24 -0
  13. package/lib/macro/defs/link.js +257 -0
  14. package/lib/macro/defs/project.js +25 -0
  15. package/lib/macro/defs/read.js +145 -0
  16. package/lib/macro/defs/remember.js +213 -0
  17. package/lib/macro/defs/search.js +661 -0
  18. package/lib/macro/defs/update.js +161 -0
  19. package/lib/macro/dreamledger.js +1398 -0
  20. package/lib/macro/facade.js +135 -0
  21. package/lib/macro/fusion.js +182 -0
  22. package/lib/macro/linkflow.js +391 -0
  23. package/lib/macro/links.js +448 -0
  24. package/lib/macro/neighbor.js +209 -0
  25. package/lib/macro/panel.js +96 -0
  26. package/lib/macro/prompt.js +139 -0
  27. package/lib/macro/provenance.js +148 -0
  28. package/lib/macro/render.js +35 -0
  29. package/lib/macro/revisions.js +253 -0
  30. package/lib/macro/shared.js +113 -0
  31. package/lib/macro/store.js +103 -0
  32. package/lib/macro/tokencost.js +90 -0
  33. package/lib/macro/tools.js +67 -0
  34. package/package.json +54 -4
  35. package/vendor/VENDOR.json +23 -0
  36. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  37. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  38. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  39. package/vendor/dsh-memory-nebula/README.md +253 -0
  40. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  41. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  42. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  43. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  44. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  45. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  46. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +317 -0
  47. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  48. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  49. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  50. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  51. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  52. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  53. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  54. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  55. package/vendor/dsh-memory-nebula/lib/host/graph.js +1663 -0
  56. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +282 -0
  57. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  58. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  59. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  60. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  61. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  62. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  63. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  64. package/vendor/dsh-memory-nebula/lib/host/recall.js +451 -0
  65. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  66. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  67. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  68. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  69. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  70. package/vendor/dsh-memory-nebula/lib/index.js +759 -0
  71. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  72. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  73. package/vendor/dsh-memory-nebula/lib/web/app.js +4159 -0
  74. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  75. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  76. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  77. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  78. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  79. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  80. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  81. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  82. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  83. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  84. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  85. package/vendor/dsh-memory-nebula/package.json +87 -0
  86. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  87. package/vendor/meow-memory/LICENSE +21 -0
  88. package/vendor/meow-memory/README.en.md +192 -0
  89. package/vendor/meow-memory/README.md +174 -0
  90. package/vendor/meow-memory/README.pt-br.md +180 -0
  91. package/vendor/meow-memory/cordis.patch.yml +7 -0
  92. package/vendor/meow-memory/lib/client.js +3344 -0
  93. package/vendor/meow-memory/lib/client.js.map +7 -0
  94. package/vendor/meow-memory/lib/index.js +9567 -0
  95. package/vendor/meow-memory/lib/index.js.map +7 -0
  96. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  97. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  98. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  99. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  100. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  101. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  102. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  103. package/vendor/meow-memory/lib/prompts/en/labels.md +98 -0
  104. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  105. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  106. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  107. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  108. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  109. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  110. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  111. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  112. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  113. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  114. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +98 -0
  115. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  116. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  117. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  118. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  119. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  120. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  121. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  122. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  123. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  124. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  125. package/vendor/meow-memory/lib/prompts/zh/labels.md +98 -0
  126. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  127. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  128. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  129. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  130. package/vendor/meow-memory/package.json +64 -0
@@ -0,0 +1,95 @@
1
+ /**
2
+ * 每轮邻域注入的预算配置($DSH_HOME/memory-nebula/inject.json)。
3
+ *
4
+ * 【当前状态:没有调用方】2026-11-18 起 lib/index.js 不再做自动邻域注入
5
+ * (它每轮改 system prompt,会把前缀缓存后整段历史打回重算),因此这个模块
6
+ * 不再被 import,inject.json 也改不了任何行为。保留它是因为按需注入若要做,
7
+ * 预算的键与范围校验逻辑可以原样复用——启用前请先补回调用点。
8
+ *
9
+ * 这份文件是给人手改的,所以每个键都要有范围:写错一个键不该让注入
10
+ * 悄悄关掉(maxRounds: null),也不该让它每轮都注入(maxRounds: "two")。
11
+ * 认不出来的值一律回到默认值,并把「哪一项没认」记下来交给调用方写日志——
12
+ * 静默回落正是这个项目栽过几次的坑。
13
+ */
14
+ import { existsSync, readFileSync } from 'node:fs'
15
+ import { join } from 'node:path'
16
+
17
+ /** 默认预算:会进 prompt 前缀,尽量保守。 */
18
+ export const INJECT_DEFAULTS = {
19
+ maxRounds: 2,
20
+ maxItems: 4,
21
+ maxChars: 900,
22
+ minWeight: 0.5,
23
+ hops: 1,
24
+ perWorkspace: 2,
25
+ perLevel: 2,
26
+ }
27
+
28
+ /** 每个键的取值范围:整数键四舍五入,比例键保留小数。 */
29
+ export const INJECT_LIMITS = {
30
+ maxRounds: { kind: 'int', min: 0, max: 5 },
31
+ maxItems: { kind: 'int', min: 1, max: 20 },
32
+ maxChars: { kind: 'int', min: 100, max: 4000 },
33
+ minWeight: { kind: 'num', min: 0, max: 1 },
34
+ hops: { kind: 'int', min: 0, max: 3 },
35
+ perWorkspace: { kind: 'int', min: 0, max: 10 },
36
+ perLevel: { kind: 'int', min: 0, max: 4 },
37
+ }
38
+
39
+ function clampOne(key, raw, notes) {
40
+ const limit = INJECT_LIMITS[key]
41
+ const fallback = INJECT_DEFAULTS[key]
42
+ if (raw === undefined) return fallback
43
+ const n = typeof raw === 'number' ? raw : Number(raw)
44
+ if (raw === null || raw === '' || !Number.isFinite(n)) {
45
+ notes.push(key + ' 不是数字(' + JSON.stringify(raw) + '),用默认值 ' + fallback)
46
+ return fallback
47
+ }
48
+ const v = limit.kind === 'int' ? Math.round(n) : n
49
+ if (v < limit.min || v > limit.max) {
50
+ const fixed = Math.max(limit.min, Math.min(limit.max, v))
51
+ notes.push(key + ' 超出 ' + limit.min + '–' + limit.max + '(收到 ' + v + '),按 ' + fixed + ' 算')
52
+ return fixed
53
+ }
54
+ return v
55
+ }
56
+
57
+ /**
58
+ * 把一份「人手写的」配置规整成安全的一份。
59
+ * @param {unknown} raw
60
+ * @returns {{ value: Record<string, number>, notes: string[] }}
61
+ */
62
+ export function normalizeInjectConfig(raw) {
63
+ const notes = []
64
+ const value = { ...INJECT_DEFAULTS }
65
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
66
+ if (raw !== undefined && raw !== null) notes.push('顶层应该是对象,整份配置被忽略')
67
+ return { value, notes }
68
+ }
69
+ for (const key of Object.keys(INJECT_DEFAULTS)) {
70
+ value[key] = clampOne(key, raw[key], notes)
71
+ }
72
+ for (const key of Object.keys(raw)) {
73
+ if (!(key in INJECT_DEFAULTS)) notes.push('不认识的键 ' + key + '(会被忽略)')
74
+ }
75
+ return { value, notes }
76
+ }
77
+
78
+ /**
79
+ * 从 <home>/memory-nebula/inject.json 读配置;文件不在就是默认值(不记 note)。
80
+ * @param {string} home DSH_HOME
81
+ * @returns {{ value: Record<string, number>, notes: string[] }}
82
+ */
83
+ export function readInjectConfig(home) {
84
+ const notes = []
85
+ const file = join(home, 'memory-nebula', 'inject.json')
86
+ let raw
87
+ try {
88
+ if (!existsSync(file)) return { value: { ...INJECT_DEFAULTS }, notes }
89
+ raw = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
90
+ } catch (err) {
91
+ notes.push('inject.json 读不动(' + (err && err.message ? err.message : String(err)) + '),整份用默认值')
92
+ return { value: { ...INJECT_DEFAULTS }, notes }
93
+ }
94
+ return normalizeInjectConfig(raw)
95
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * 统一注入账本 —— 「哪些记忆已经给模型看过了」
3
+ *
4
+ * 为什么需要它:星图不是唯一的记忆来源。meow-memory 每轮注入它自己的条目,
5
+ * hindsight / openviking 也可能注入,星图再注入「邻居」时如果不知道别人已经喂过什么,
6
+ * 就会重复、抢预算、把上下文塞满同一件事。
7
+ *
8
+ * 这一层把三路信号合成一个集合:
9
+ *
10
+ * 1. meow 的会话账本 <cwd>/.dsh-meow/sessions/<sid>.json(只读,别人的)
11
+ * 2. 星图自己的注入记录 $DSH_HOME/memory-nebula/injected/<sid>.json(可写)
12
+ * 3. 外部插件的声明 同目录下 <sid>.json 里的 external 段(别人可以往里写)
13
+ *
14
+ * 另外维护一个跨会话冷却表:
15
+ *
16
+ * $DSH_HOME/memory-nebula/injected/_global.json { uid: lastInjectedAt }
17
+ *
18
+ * 冷却的意义:一条高价值邻居不该每个新会话都占一次预算。默认 7 天内不再主动推同一条,
19
+ * 除非它被显式检索(那是用户/模型自己要点,不冷却)。
20
+ */
21
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync, readdirSync } from 'node:fs'
22
+ import { join, dirname } from 'node:path'
23
+ import { nebulaHome } from './adapters/util.js'
24
+
25
+ export const GLOBAL_COOLDOWN_MS = 7 * 24 * 3600 * 1000
26
+ /** 单文件最大读取(防呆:账本不该有几十 MB) */
27
+ const MAX_LEDGER_BYTES = 4 * 1024 * 1024
28
+
29
+ export function injectedDir() {
30
+ return join(nebulaHome(), 'injected')
31
+ }
32
+
33
+ export function ledgerFile(sessionId) {
34
+ const safe = String(sessionId || 'unknown').replace(/[^\w.@-]+/g, '%')
35
+ return join(injectedDir(), safe + '.json')
36
+ }
37
+
38
+ function globalFile() {
39
+ return join(injectedDir(), '_global.json')
40
+ }
41
+
42
+ function readJson(file) {
43
+ try {
44
+ if (!existsSync(file)) return null
45
+ const st = statSync(file)
46
+ if (!st.isFile() || st.size > MAX_LEDGER_BYTES) return null
47
+ return JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
48
+ } catch {
49
+ return null
50
+ }
51
+ }
52
+
53
+ function writeJson(file, value) {
54
+ try {
55
+ mkdirSync(dirname(file), { recursive: true })
56
+ writeFileSync(file, JSON.stringify(value), 'utf8')
57
+ return true
58
+ } catch {
59
+ return false
60
+ }
61
+ }
62
+
63
+ /**
64
+ * 读本会话的星图账本。
65
+ * @returns {{seen: Record<string, number>, injected: string[], external: Record<string, number>, updatedAt: number}}
66
+ */
67
+ export function readLedger(sessionId) {
68
+ const raw = readJson(ledgerFile(sessionId)) || {}
69
+ const seen = raw.seen && typeof raw.seen === 'object' ? raw.seen : {}
70
+ const external = raw.external && typeof raw.external === 'object' ? raw.external : {}
71
+ return {
72
+ seen,
73
+ external,
74
+ injected: Array.isArray(raw.injected) ? raw.injected : [],
75
+ updatedAt: Number(raw.updatedAt) || 0,
76
+ }
77
+ }
78
+
79
+ /**
80
+ * 把一批 uid 记为「已见」。
81
+ * @param {string} sessionId
82
+ * @param {string[]} uids
83
+ * @param {string} by 来源标记:nebula:inject / nebula:tool / external:<name>
84
+ */
85
+ export function markSeen(sessionId, uids, by = 'nebula:inject') {
86
+ const list = (uids || []).map((u) => String(u || '').trim()).filter(Boolean)
87
+ if (list.length === 0) return { marked: 0 }
88
+ const file = ledgerFile(sessionId)
89
+ const cur = readJson(file) || {}
90
+ const now = Date.now()
91
+ cur.seen = cur.seen && typeof cur.seen === 'object' ? cur.seen : {}
92
+ cur.injected = Array.isArray(cur.injected) ? cur.injected : []
93
+ const external = String(by).startsWith('external')
94
+ if (external) cur.external = cur.external && typeof cur.external === 'object' ? cur.external : {}
95
+ for (const uid of list) {
96
+ cur.seen[uid] = now
97
+ if (external) cur.external[uid] = now
98
+ if (!cur.injected.includes(uid)) cur.injected.push(uid)
99
+ }
100
+ // 账本别无限长:只留最近 2000 条
101
+ if (cur.injected.length > 2000) cur.injected = cur.injected.slice(-2000)
102
+ cur.updatedAt = now
103
+ cur.sessionId = String(sessionId || '')
104
+ writeJson(file, cur)
105
+ return { marked: list.length }
106
+ }
107
+
108
+ /**
109
+ * 合并「谁已经看过什么」,得到本轮可用的已见集合。
110
+ *
111
+ * @param {string} sessionId
112
+ * @param {{injected?: string[], searched?: string[], accessed?: string[], written?: string[]}} meowLedger
113
+ * meow 的会话账本(可空)
114
+ * @returns {Set<string>} uid 集合
115
+ */
116
+ export function seenSet(sessionId, meowLedger = null) {
117
+ const out = new Set()
118
+ const add = (v) => {
119
+ if (v === null || v === undefined) return
120
+ const s = String(v).trim()
121
+ if (!s) return
122
+ out.add(s)
123
+ // 兼容完整 id:同时收裸 uid
124
+ const parts = s.split(':')
125
+ if (parts.length > 1) out.add(parts[parts.length - 1])
126
+ }
127
+ for (const key of ['injected', 'searched', 'accessed', 'written']) {
128
+ const list = meowLedger && Array.isArray(meowLedger[key]) ? meowLedger[key] : []
129
+ for (const v of list) add(v)
130
+ }
131
+ const mine = readLedger(sessionId)
132
+ for (const uid of Object.keys(mine.seen)) add(uid)
133
+ for (const uid of Object.keys(mine.external)) add(uid)
134
+ return out
135
+ }
136
+
137
+ /** 读全局冷却表:uid → lastInjectedAt */
138
+ export function readCooldown() {
139
+ const raw = readJson(globalFile()) || {}
140
+ const map = new Map()
141
+ const now = Date.now()
142
+ for (const [uid, at] of Object.entries(raw)) {
143
+ const t = Number(at) || 0
144
+ if (t && now - t < GLOBAL_COOLDOWN_MS) map.set(uid, t)
145
+ }
146
+ return map
147
+ }
148
+
149
+ /** 写冷却表(顺手裁掉过期项)。 */
150
+ export function markCooldown(uids) {
151
+ const list = (uids || []).map((u) => String(u || '').trim()).filter(Boolean)
152
+ if (list.length === 0) return { marked: 0 }
153
+ const now = Date.now()
154
+ const cur = readJson(globalFile()) || {}
155
+ const next = {}
156
+ for (const [uid, at] of Object.entries(cur)) {
157
+ const t = Number(at) || 0
158
+ if (t && now - t < GLOBAL_COOLDOWN_MS) next[uid] = t
159
+ }
160
+ for (const uid of list) next[uid] = now
161
+ writeJson(globalFile(), next)
162
+ return { marked: list.length }
163
+ }
164
+
165
+ /** 体检用:账本规模。 */
166
+ export function ledgerStats() {
167
+ const dir = injectedDir()
168
+ let files = []
169
+ try {
170
+ files = readdirSync(dir).filter((n) => n.endsWith('.json'))
171
+ } catch {
172
+ files = []
173
+ }
174
+ return { dir, sessions: files.length, cooldown: readCooldown().size }
175
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * 引擎热载(hot engine)
3
+ *
4
+ * 为什么要这个:DSH 的插件模块在进程里 import 一次就进缓存了,
5
+ * 改 lib/host/*.js 不会重新执行。为了「不重启 DSH 也能迭代星图的算法」,
6
+ * 这里把引擎文件按 mtime 复制到一个带版本号的目录,再从那份新文件 import。
7
+ * 新版 URL 不同 → Node 重新解析整棵树 → 拿到改后的代码。
8
+ *
9
+ * v0.3 起:**递归枚举** lib/host 下所有 .js(含 adapters/ 子目录),
10
+ * 新增适配器/模块不用再回来改这份清单。
11
+ *
12
+ * 换引擎时:新实例先建好图,再原子替换引用;旧实例停掉 watcher。
13
+ * 数据都在 sidecar 库里,换引擎不丢东西。
14
+ */
15
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
16
+ import { dirname, join } from 'node:path'
17
+ import { fileURLToPath, pathToFileURL } from 'node:url'
18
+ import { nebulaHome } from './sources.js'
19
+
20
+ const HERE = dirname(fileURLToPath(import.meta.url))
21
+
22
+ /** 不进热载清单的文件:入口本身静态加载,改了必须重启。 */
23
+ const SKIP = new Set(['live.js'])
24
+
25
+ /** 递归列出引擎文件(相对路径,用 / 分隔)。 */
26
+ function listEngineFiles() {
27
+ const out = []
28
+ const walk = (rel) => {
29
+ let entries = []
30
+ try {
31
+ entries = readdirSync(rel ? join(HERE, rel) : HERE, { withFileTypes: true })
32
+ } catch {
33
+ return
34
+ }
35
+ for (const entry of entries) {
36
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name
37
+ if (entry.isDirectory()) {
38
+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue
39
+ walk(childRel)
40
+ continue
41
+ }
42
+ if (!entry.name.endsWith('.js')) continue
43
+ if (SKIP.has(childRel)) continue
44
+ out.push(childRel)
45
+ }
46
+ }
47
+ walk('')
48
+ return out.sort()
49
+ }
50
+
51
+ /** 文件清单 + mtime 指纹;1.5 秒内复用,避免每个 HTTP 请求都 stat 一遍。 */
52
+ let stampCache = { at: 0, value: 0, files: [] }
53
+ export function engineStamp() {
54
+ const now = Date.now()
55
+ if (now - stampCache.at < 1500 && stampCache.files.length > 0) return stampCache.value
56
+ const files = listEngineFiles()
57
+ let max = 0
58
+ for (const rel of files) {
59
+ try {
60
+ max = Math.max(max, statSync(join(HERE, rel)).mtimeMs)
61
+ } catch {
62
+ /* 文件缺失就当没变 */
63
+ }
64
+ }
65
+ const value = Math.round(max)
66
+ stampCache = { at: now, value, files }
67
+ return value
68
+ }
69
+
70
+ /** 每个 mtime 版本建一个目录。改几十次就攒出一堆(本机曾攒到 110 个 / 10MB),只留最近 3 个 + 当前。 */
71
+ function pruneEngineDirs(current) {
72
+ const root = join(nebulaHome(), 'engine')
73
+ let names = []
74
+ try {
75
+ names = readdirSync(root, { withFileTypes: true })
76
+ .filter((d) => d.isDirectory())
77
+ .map((d) => d.name)
78
+ .sort()
79
+ } catch {
80
+ return
81
+ }
82
+ const keep = new Set(names.slice(-3))
83
+ keep.add(current)
84
+ for (const name of names) {
85
+ if (keep.has(name)) continue
86
+ try {
87
+ rmSync(join(root, name), { recursive: true, force: true })
88
+ } catch {
89
+ /* 正在被别的版本用着就下次再说 */
90
+ }
91
+ }
92
+ }
93
+
94
+ export class LiveEngine {
95
+ constructor({ onLog } = {}) {
96
+ this.onLog = onLog || (() => {})
97
+ this.instance = null
98
+ this.stamp = 0
99
+ this.loading = null
100
+ this.failures = 0
101
+ this.retryAt = 0
102
+ }
103
+
104
+ /** 同步检查:代码变了就在后台换引擎,立刻返回当前实例。 */
105
+ sync() {
106
+ const stamp = engineStamp()
107
+ if (this.instance && stamp === this.stamp) return this.instance
108
+ if (this.loading) return this.instance
109
+ // 失败后必须退避:轮询每 45ms 一次,一次 import 失败会变成一分钟上千条同样的栈,
110
+ // 日志能被撑到几百兆(0.3.0 之前真的发生过)。
111
+ if (this.retryAt && Date.now() < this.retryAt) return this.instance
112
+ this.loading = this.#load(stamp)
113
+ .then((next) => {
114
+ this.failures = 0
115
+ this.retryAt = 0
116
+ return next
117
+ })
118
+ .catch((err) => {
119
+ this.failures += 1
120
+ const backoff = Math.min(60_000, 1000 * 2 ** Math.min(this.failures, 6))
121
+ this.retryAt = Date.now() + backoff
122
+ this.onLog(`引擎热载失败(第 ${this.failures} 次,${Math.round(backoff / 1000)}s 后重试):${err?.stack || err}`)
123
+ })
124
+ .finally(() => {
125
+ this.loading = null
126
+ })
127
+ return this.instance
128
+ }
129
+
130
+ /** 确保有实例(首次用)。 */
131
+ async ensure() {
132
+ if (this.instance && engineStamp() === this.stamp) return this.instance
133
+ if (this.loading) await this.loading
134
+ if (this.instance && engineStamp() === this.stamp) return this.instance
135
+ await this.#load(engineStamp())
136
+ return this.instance
137
+ }
138
+
139
+ async #load(stamp) {
140
+ const dir = join(nebulaHome(), 'engine', String(stamp))
141
+ const files = stampCache.files.length > 0 ? stampCache.files : listEngineFiles()
142
+ if (!existsSync(join(dir, 'nebula.js'))) {
143
+ mkdirSync(dir, { recursive: true })
144
+ for (const rel of files) {
145
+ const target = join(dir, rel)
146
+ mkdirSync(dirname(target), { recursive: true })
147
+ copyFileSync(join(HERE, rel), target)
148
+ }
149
+ }
150
+ pruneEngineDirs(String(stamp))
151
+ const mod = await import(pathToFileURL(join(dir, 'nebula.js')).href)
152
+ const next = new mod.Nebula()
153
+ await next.refresh()
154
+ const prev = this.instance
155
+ this.instance = next
156
+ this.stamp = stamp
157
+ if (prev) {
158
+ try {
159
+ prev.stopWatching()
160
+ } catch {
161
+ /* ignore */
162
+ }
163
+ }
164
+ try {
165
+ next.startWatching(12000)
166
+ } catch {
167
+ /* ignore */
168
+ }
169
+ this.onLog(`引擎就绪 build=${stamp}(记忆 ${next.graph?.nodes?.length ?? 0} 条,模块 ${files.length} 个)`)
170
+ return next
171
+ }
172
+ }
173
+
174
+ /**
175
+ * 门面:调用方拿到的对象永远指向「当前那一版引擎」。
176
+ * 属性读、方法调都实时转发,不会抓到旧实例。
177
+ */
178
+ export function liveFacade(live) {
179
+ return new Proxy(
180
+ {},
181
+ {
182
+ get(_target, prop) {
183
+ const inst = live.sync()
184
+ if (!inst) {
185
+ if (prop === 'refresh' || prop === 'ensure') return () => live.ensure()
186
+ return undefined
187
+ }
188
+ const value = inst[prop]
189
+ if (typeof value !== 'function') return value
190
+ return (...args) => {
191
+ const now = live.instance || inst
192
+ return now[prop](...args)
193
+ }
194
+ },
195
+ set(_target, prop, value) {
196
+ if (live.instance) live.instance[prop] = value
197
+ return true
198
+ },
199
+ has(_target, prop) {
200
+ return live.instance ? prop in live.instance : false
201
+ },
202
+ },
203
+ )
204
+ }