dsh-memu-memory 1.3.1 → 1.3.2

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 (46) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -1
  4. package/docs/contributing.md +2 -2
  5. package/docs/env-and-commands.md +12 -1
  6. package/docs/memory-semantics.md +8 -2
  7. package/docs/troubleshooting.md +9 -6
  8. package/lib/auto-link/apply.js +249 -0
  9. package/lib/auto-link/candidates.js +155 -0
  10. package/lib/auto-link/decide.js +304 -0
  11. package/lib/auto-link/normalize.js +99 -0
  12. package/lib/auto-link/policy.js +42 -0
  13. package/lib/auto-link/suppression.js +101 -0
  14. package/lib/auto-link/terminology.js +265 -0
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +1412 -69
  17. package/lib/graph.js +269 -18
  18. package/lib/memory.js +11 -0
  19. package/lib/memu.js +7 -6
  20. package/lib/private-links.js +105 -137
  21. package/lib/private.js +138 -38
  22. package/lib/rpc.js +67 -7
  23. package/lib/state.js +7 -2
  24. package/lib/tools.js +4 -2
  25. package/lib/webui/graph-LICENSE.txt +1 -62
  26. package/lib/webui/graph-view.bundle.js +1 -1
  27. package/lib/webui/graph-view.js +891 -124
  28. package/lib/webui/standalone.js +3 -3
  29. package/package.json +1 -2
  30. package/scripts/build-graph.mjs +3 -3
  31. package/scripts/check-graph-browser.mjs +106 -23
  32. package/scripts/rebuild-auto-links.mjs +252 -0
  33. package/tests/audit-regression.test.mjs +11 -8
  34. package/tests/auto-link-candidates.test.mjs +161 -0
  35. package/tests/auto-link-decide.test.mjs +512 -0
  36. package/tests/auto-link-migration.test.mjs +133 -0
  37. package/tests/client-render.test.mjs +7 -6
  38. package/tests/consolidation-fork.test.mjs +148 -0
  39. package/tests/cycle.test.mjs +1 -1
  40. package/tests/graph-view.test.mjs +163 -21
  41. package/tests/graph.test.mjs +5 -0
  42. package/tests/help-page.test.mjs +3 -3
  43. package/tests/memu-resident-route.test.mjs +130 -0
  44. package/tests/private-links.test.mjs +81 -45
  45. package/tests/stubs/child-process-spy.mjs +14 -0
  46. package/tests/tools.test.mjs +24 -18
@@ -0,0 +1,265 @@
1
+ // Nomination layer: local, zero-token term statistics used ONLY to rank a review
2
+ // queue. Nothing here decides that an entity exists or that an edge is written —
3
+ // statistical scores live and die inside the candidate list (DESIGN P4/P9).
4
+
5
+ import { AUTOLINK_POLICY_V3 } from './policy.js'
6
+ import { normalizeForIndex } from './normalize.js'
7
+
8
+ const CJK_RUN = /[\u3400-\u9fff\uf900-\ufaff]+/g
9
+ const LATIN_RUN = /[a-z0-9][a-z0-9._-]*/g
10
+ const AV_CAP = 24
11
+
12
+ // Characters that make a CJK string grammatical glue rather than a name.
13
+ const FUNCTION_CHARS = new Set('的了是和与也就都很又还你我他她它们这那哪什么吗呢吧啊呀哦嗯之其而且但却被让给对从向于为及或并着过得地有不想要会可能可以说去来'.split(''))
14
+ // Measure-word templates: 一条/两只/这个/那些… A name never starts with one.
15
+ const MEASURE_PREFIX = /^(一|两|三|几|每|这|那|半)?[条只把张个位次件场顿盘杯碗袋包串支根颗头匹群套双对份页篇段句声口]/
16
+
17
+ const QUOTE_RE = /[「『《"']([^」』》"']{1,20})[」』》"']/g
18
+ const INTRO_RE = /(?:叫|名叫|名字(?:是|叫|为)?|称呼(?:是|为)?|自称|username|nickname)([^\n。]{0,6})/gi
19
+
20
+ /** Terms whose surface shape cannot be a name on its own (ranking hint only). */
21
+ export function looksGeneric(token) {
22
+ const text = String(token || '')
23
+ if (!text) return true
24
+ if ([...text].some(ch => FUNCTION_CHARS.has(ch))) return true
25
+ if (MEASURE_PREFIX.test(text) && text.length <= 3) return true
26
+ return false
27
+ }
28
+
29
+ function isLatinTerm(term) {
30
+ return /^[a-z0-9]/.test(term) && !/[\u3400-\u9fff\uf900-\ufaff]/.test(term)
31
+ }
32
+
33
+ function addNgrams(set, text, policy) {
34
+ const value = String(text || '').normalize('NFKC').toLowerCase()
35
+ for (const run of value.match(CJK_RUN) || []) {
36
+ for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
37
+ for (let i = 0; i + size <= run.length; i += 1) set.add(run.slice(i, i + size))
38
+ }
39
+ }
40
+ for (const token of value.match(LATIN_RUN) || []) {
41
+ if (token.length >= policy.latinMin && token.length <= policy.latinMax) set.add(token)
42
+ }
43
+ }
44
+
45
+ /** Quoted spans and name-intro neighbours, collected once per library. */
46
+ function surfaceEvidence(docs, policy) {
47
+ const quoted = new Set()
48
+ const intro = new Set()
49
+ for (const { text } of docs) {
50
+ const source = String(text || '')
51
+ let match
52
+ QUOTE_RE.lastIndex = 0
53
+ while ((match = QUOTE_RE.exec(source))) addNgrams(quoted, match[1], policy)
54
+ INTRO_RE.lastIndex = 0
55
+ while ((match = INTRO_RE.exec(source))) addNgrams(intro, match[1], policy)
56
+ }
57
+ return { quoted, intro }
58
+ }
59
+
60
+ function llrFor(term, tf, unigram, ngramTotals) {
61
+ if (term.length < 2) return 0
62
+ const prefix = term.slice(0, -1)
63
+ const suffix = term.slice(1)
64
+ const countOf = (part) => (part.length === 1 ? (unigram.get(part) || 0) : (tf.get(part) || 0))
65
+ const a = tf.get(term) || 0
66
+ const b = Math.max(0, countOf(prefix) - a)
67
+ const c = Math.max(0, countOf(suffix) - a)
68
+ const total = Math.max(1, ngramTotals.get(term.length) || 0)
69
+ const d = Math.max(0, total - a - b - c)
70
+ const rows = [
71
+ [a, b, a + b],
72
+ [c, d, c + d],
73
+ ]
74
+ const cols = [a + c, b + d, a + b + c + d]
75
+ let llr = 0
76
+ for (let i = 0; i < 2; i += 1) {
77
+ for (let j = 0; j < 2; j += 1) {
78
+ const observed = rows[i][j]
79
+ if (!observed) continue
80
+ const expected = (rows[i][2] * cols[j]) / Math.max(1, cols[2])
81
+ if (expected > 0) llr += observed * Math.log(observed / expected)
82
+ }
83
+ }
84
+ return 2 * llr
85
+ }
86
+
87
+ function pmiFor(term, tf, unigram, totalChars) {
88
+ if (!totalChars) return 0
89
+ const chars = [...term]
90
+ const termCount = tf.get(term) || 0
91
+ if (!termCount) return 0
92
+ let product = 1
93
+ for (const ch of chars) product *= (unigram.get(ch) || 0) / totalChars
94
+ if (product <= 0) return 0
95
+ return Math.log2((termCount / totalChars) / product)
96
+ }
97
+
98
+ /**
99
+ * Single pass over title+content per document. Returns Map(term -> statistics):
100
+ * tf/df/titleDf, boundary variety, cohesion/freedom, PMI, LLR and the surface
101
+ * shape bits (latin, quoted/intro membership is applied during ranking).
102
+ */
103
+ export function buildTermStats(entries, policy = AUTOLINK_POLICY_V3) {
104
+ const tf = new Map()
105
+ const df = new Map()
106
+ const titleDf = new Map()
107
+ const unigram = new Map()
108
+ const leftSets = new Map()
109
+ const rightSets = new Map()
110
+ const ngramTotals = new Map()
111
+ let totalChars = 0
112
+
113
+ const bump = (map, key, by = 1) => map.set(key, (map.get(key) || 0) + by)
114
+ const addNeighbour = (map, key, value) => {
115
+ let set = map.get(key)
116
+ if (!set) { set = new Set(); map.set(key, set) }
117
+ if (set.size < AV_CAP) set.add(value)
118
+ }
119
+
120
+ for (const { text, title } of entries) {
121
+ const normalized = String(text || '').normalize('NFKC').toLowerCase()
122
+ const perDoc = new Set()
123
+ for (const match of normalized.matchAll(CJK_RUN)) {
124
+ const run = match[0]
125
+ const start = match.index || 0
126
+ totalChars += [...run].length
127
+ for (const ch of run) bump(unigram, ch)
128
+ for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
129
+ for (let i = 0; i + size <= run.length; i += 1) {
130
+ const term = run.slice(i, i + size)
131
+ bump(tf, term)
132
+ bump(ngramTotals, size)
133
+ perDoc.add(term)
134
+ const offset = Math.max(0, start) + i
135
+ addNeighbour(leftSets, term, offset > 0 ? normalized[offset - 1] : '^')
136
+ addNeighbour(rightSets, term, offset + size < normalized.length ? normalized[offset + size] : '$')
137
+ }
138
+ }
139
+ }
140
+ for (const token of normalized.match(LATIN_RUN) || []) {
141
+ if (token.length < policy.latinMin || token.length > policy.latinMax || /^\d+$/.test(token)) continue
142
+ bump(tf, token)
143
+ bump(ngramTotals, token.length)
144
+ perDoc.add(token)
145
+ }
146
+ for (const term of perDoc) bump(df, term)
147
+ const normalizedTitle = String(title || '').normalize('NFKC').toLowerCase()
148
+ if (normalizedTitle) {
149
+ const titleTerms = new Set()
150
+ for (const run of normalizedTitle.match(CJK_RUN) || []) {
151
+ for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
152
+ for (let i = 0; i + size <= run.length; i += 1) titleTerms.add(run.slice(i, i + size))
153
+ }
154
+ }
155
+ for (const token of normalizedTitle.match(LATIN_RUN) || []) {
156
+ if (token.length >= policy.latinMin && token.length <= policy.latinMax) titleTerms.add(token)
157
+ }
158
+ for (const term of titleTerms) bump(titleDf, term)
159
+ }
160
+ }
161
+
162
+ const stats = new Map()
163
+ for (const [term, count] of tf) {
164
+ if (/^\d+$/.test(term)) continue
165
+ const latin = isLatinTerm(term)
166
+ const leftPart = term.slice(0, -1)
167
+ const rightPart = term.slice(1)
168
+ const base = (part) => (part.length === 1 ? (unigram.get(part) || 1) : (tf.get(part) || 1))
169
+ const cohesion = latin ? 1 : count / Math.max(1, Math.min(base(leftPart), base(rightPart)))
170
+ const avLeft = latin ? Math.min(3, df.get(term) || 1) : (leftSets.get(term)?.size || 0)
171
+ const avRight = latin ? Math.min(3, df.get(term) || 1) : (rightSets.get(term)?.size || 0)
172
+ stats.set(term, {
173
+ term,
174
+ tf: count,
175
+ df: df.get(term) || 0,
176
+ titleDf: titleDf.get(term) || 0,
177
+ cohesion,
178
+ avLeft,
179
+ avRight,
180
+ freedom: Math.min(avLeft, avRight),
181
+ pmi: latin ? 0 : pmiFor(term, tf, unigram, totalChars),
182
+ llr: latin ? 0 : llrFor(term, tf, unigram, ngramTotals),
183
+ latin,
184
+ })
185
+ }
186
+ return stats
187
+ }
188
+
189
+ function scoreOf(stat, { size, quoted, mixed, intro, titleBoost, lexiconTier1, lexiconModel, policy }) {
190
+ const rarity = 1 - Math.min(1, stat.df / Math.max(4, size * 0.25))
191
+ const boundary = Math.min(stat.avLeft, stat.avRight)
192
+ const pmi = Math.max(0, Math.min(12, stat.pmi)) / 12
193
+ const llr = Math.max(0, Math.min(1, Math.log10(1 + stat.llr) / 6))
194
+ const titleFocus = stat.titleDf >= policy.minTitleDf ? Math.min(1, stat.titleDf / 3) : 0
195
+ return boundary * 0.35
196
+ + Math.min(stat.cohesion, 3) * 0.35
197
+ + rarity * 0.8
198
+ + pmi * 0.5
199
+ + llr * 0.5
200
+ + titleFocus * 0.6
201
+ + (quoted ? 2.5 : 0)
202
+ + (mixed ? 2.0 : 0)
203
+ + (intro ? 2.0 : 0)
204
+ + (titleBoost ? 1.2 : 0)
205
+ + (lexiconTier1 ? 2.5 : 0)
206
+ + (lexiconModel ? 0.8 : 0)
207
+ }
208
+
209
+ /**
210
+ * Two review tiers. Tier 1 carries surface evidence (quote / identifier /
211
+ * name-intro / user lexicon) and is cheap to confirm; tier 2 is statistical
212
+ * only. Scores order the queue; they never gate an edge write.
213
+ */
214
+ export function rankCandidates(entries, stats, { policy = AUTOLINK_POLICY_V3, lexiconUser = new Set(), lexiconModel = new Set() } = {}) {
215
+ const docs = entries.map(({ text, title }) => ({ text: `${title || ''}\n${text || ''}` }))
216
+ const { quoted, intro } = surfaceEvidence(docs, policy)
217
+ const size = Math.max(1, entries.length)
218
+ const tier1 = []
219
+ const tier2 = []
220
+ for (const stat of stats.values()) {
221
+ const term = stat.term
222
+ if (stat.df < policy.minDf) continue
223
+ if (stat.df > Math.max(policy.minDf, Math.floor(size * policy.maxDfRatio))) continue
224
+ if (looksGeneric(term)) continue
225
+ // Boundary variety is a ranking feature, not a hard gate (DESIGN §9.1): a real
226
+ // name that only ever appears at a title's start/end still belongs in the queue.
227
+ if (/^\d{4}[-/年.]\d{1,2}/.test(term)) continue
228
+ if ((term.match(/\d/g) || []).length >= Math.ceil(term.length / 2)) continue
229
+ const normalized = normalizeForIndex(term)
230
+ const isQuoted = quoted.has(term)
231
+ const isMixed = /[a-z].*\d|\d.*[a-z]/i.test(term)
232
+ const isIntro = intro.has(term)
233
+ const lexiconTier1 = lexiconUser.has(normalized)
234
+ const lexiconModelHit = !lexiconTier1 && lexiconModel.has(normalized)
235
+ const titleBoost = stat.titleDf >= policy.minTitleDf
236
+ const row = {
237
+ term,
238
+ score: scoreOf(stat, { size, quoted: isQuoted, mixed: isMixed, intro: isIntro, titleBoost, lexiconTier1, lexiconModel: lexiconModelHit, policy }),
239
+ df: stat.df,
240
+ tf: stat.tf,
241
+ titleDf: stat.titleDf,
242
+ cohesion: Number(stat.cohesion.toFixed(2)),
243
+ avLeft: stat.avLeft,
244
+ avRight: stat.avRight,
245
+ freedom: stat.freedom,
246
+ pmi: Number(stat.pmi.toFixed(2)),
247
+ llr: Number(stat.llr.toFixed(2)),
248
+ quoted: isQuoted,
249
+ mixed: isMixed,
250
+ intro: isIntro,
251
+ lexicon: lexiconTier1 ? 'user' : (lexiconModelHit ? 'model-proposal' : null),
252
+ }
253
+ if (isQuoted || isMixed || isIntro || lexiconTier1) tier1.push(row)
254
+ else tier2.push(row)
255
+ }
256
+ const byScore = (a, b) => b.score - a.score || a.term.localeCompare(b.term)
257
+ tier1.sort(byScore)
258
+ tier2.sort(byScore)
259
+ return {
260
+ tier1: tier1.slice(0, policy.tier1Max),
261
+ tier2: tier2.slice(0, policy.tier2Max),
262
+ }
263
+ }
264
+
265
+ export default { buildTermStats, rankCandidates, looksGeneric }
@@ -54,9 +54,9 @@ export const RUNTIME_STATE = Object.freeze([
54
54
  { layer: 'temporary-map', file: 'lib/inbound.js:13', name: 'calls', keyedBy: 'sessionId', clearedBy: 'tool/result or turn/end' },
55
55
  { layer: 'temporary-map', file: 'lib/inbound.js:14', name: 'sessions', keyedBy: 'sessionId', clearedBy: 'session/disposed (releaseInboundSession)' },
56
56
  { layer: 'temporary-map', file: 'lib/media.js:19', name: 'captures', keyedBy: 'sessionId', clearedBy: 'capture settle' },
57
- { layer: 'temporary-map', file: 'lib/private.js:805', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
57
+ { layer: 'temporary-map', file: 'lib/private.js:893', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
58
58
  { layer: 'temporary-map', file: 'lib/curator.js:56', name: 'jobs', keyedBy: 'job id', clearedBy: 'curation settle' },
59
- { layer: 'cache', file: 'lib/state.js:1215', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
59
+ { layer: 'cache', file: 'lib/state.js:1220', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
60
60
  { layer: 'cache', file: 'lib/paths.js:52', name: 'readFailures', keyedBy: 'absolute file', clearedBy: 'a later successful read' },
61
61
  ])
62
62