@zhangfeiyue/dsh-long-term-memory 0.0.0-stage → 1.1.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/README.md +96 -2
- package/client.js +580 -0
- package/cordis.patch.yml +9 -0
- package/docs/DETAIL.md +226 -0
- package/icon.svg +18 -0
- package/index.js +483 -0
- package/lib/board.js +178 -0
- package/lib/config.js +133 -0
- package/lib/consolidate.js +162 -0
- package/lib/dashboard.js +101 -0
- package/lib/domains.js +185 -0
- package/lib/extract.js +198 -0
- package/lib/profile.js +167 -0
- package/lib/records.js +197 -0
- package/lib/render.js +181 -0
- package/lib/retrieval.js +217 -0
- package/lib/store.js +338 -0
- package/lib/tools.js +422 -0
- package/lib/util.js +94 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +53 -4
package/lib/config.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin settings resolution.
|
|
3
|
+
*
|
|
4
|
+
* Precedence is defaults → `<storeDir>/config.json` → the composition row's
|
|
5
|
+
* `config`. The JSON file lets a user retune the plugin without touching the
|
|
6
|
+
* profile patch, and the row still wins when a deployment wants a fixed value.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-long-term-memory/config
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import fs from 'node:fs'
|
|
12
|
+
import os from 'node:os'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
|
|
15
|
+
/** Default harness home directory. */
|
|
16
|
+
export function defaultDshHome() {
|
|
17
|
+
return process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Built-in defaults; every one of them is safe to run unattended. */
|
|
21
|
+
export const DEFAULTS = {
|
|
22
|
+
/** Where memory records live. Deliberately outside every workspace. */
|
|
23
|
+
storeDir: path.join(defaultDshHome(), 'long-term-memory'),
|
|
24
|
+
/** Hard cap on retained records before consolidation archives the weakest. */
|
|
25
|
+
maxRecords: 5000,
|
|
26
|
+
/** Character budget for one injected memory block. */
|
|
27
|
+
maxInjectChars: 2400,
|
|
28
|
+
/** Candidate count considered by retrieval for injection. */
|
|
29
|
+
injectLimit: 12,
|
|
30
|
+
/** Maximum results returned by `memory_search`. */
|
|
31
|
+
searchLimit: 20,
|
|
32
|
+
/** Minimum milliseconds between automatic consolidations (default 6 hours). */
|
|
33
|
+
consolidateIntervalMs: 6 * 60 * 60 * 1000,
|
|
34
|
+
/** Age in days after which unused low-value trivia is archived. */
|
|
35
|
+
staleDays: 180,
|
|
36
|
+
/** Capture explicit "remember this" instructions from user messages. */
|
|
37
|
+
autoExtract: true,
|
|
38
|
+
/** Capture open items from `todo/write` snapshots as resumable tasks. */
|
|
39
|
+
taskCapture: true,
|
|
40
|
+
/** Refresh the injected block at most this often per session (default 5 min). */
|
|
41
|
+
injectRefreshMs: 5 * 60 * 1000,
|
|
42
|
+
/**
|
|
43
|
+
* Path or repository patterns that pin a workspace to a work domain.
|
|
44
|
+
* Each entry is `{ pattern, domain }`; `pattern` is a regular expression source
|
|
45
|
+
* (a plain substring also works). First match wins, before the built-in
|
|
46
|
+
* directory heuristics.
|
|
47
|
+
*/
|
|
48
|
+
domains: [],
|
|
49
|
+
/** Per-layer character budgets inside one injected block. */
|
|
50
|
+
profileBudgets: { persona: 400, work: 500, project: 520, tasks: 400 },
|
|
51
|
+
/** Minimum importance for a record to enter the personal profile. */
|
|
52
|
+
personaMinImportance: 4,
|
|
53
|
+
/** Minimum importance for a record to enter a work profile. */
|
|
54
|
+
workMinImportance: 3,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Coerce one setting, falling back to `fallback` when it is unusable. */
|
|
58
|
+
function coerce(key, value, fallback) {
|
|
59
|
+
if (value === undefined || value === null) return fallback
|
|
60
|
+
if (key === 'storeDir') return typeof value === 'string' && value.trim().length > 0 ? path.resolve(value.trim()) : fallback
|
|
61
|
+
if (key === 'autoExtract' || key === 'taskCapture') return typeof value === 'boolean' ? value : fallback
|
|
62
|
+
if (key === 'domains') {
|
|
63
|
+
if (!Array.isArray(value)) return fallback
|
|
64
|
+
return value
|
|
65
|
+
.filter(entry => entry !== null && typeof entry === 'object'
|
|
66
|
+
&& typeof entry.pattern === 'string' && entry.pattern.trim().length > 0
|
|
67
|
+
&& typeof entry.domain === 'string')
|
|
68
|
+
.map(entry => ({ pattern: entry.pattern.trim(), domain: entry.domain.trim().toLowerCase() }))
|
|
69
|
+
}
|
|
70
|
+
if (key === 'profileBudgets') {
|
|
71
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return fallback
|
|
72
|
+
const budgets = { ...fallback }
|
|
73
|
+
for (const name of Object.keys(fallback)) {
|
|
74
|
+
const numeric = Number(value[name])
|
|
75
|
+
if (Number.isFinite(numeric) && numeric > 0) budgets[name] = Math.min(4000, Math.trunc(numeric))
|
|
76
|
+
}
|
|
77
|
+
return budgets
|
|
78
|
+
}
|
|
79
|
+
const numeric = Number(value)
|
|
80
|
+
if (!Number.isFinite(numeric)) return fallback
|
|
81
|
+
if (key === 'maxRecords') return Math.max(50, Math.min(200_000, Math.trunc(numeric)))
|
|
82
|
+
if (key === 'maxInjectChars') return Math.max(400, Math.min(20_000, Math.trunc(numeric)))
|
|
83
|
+
if (key === 'injectLimit') return Math.max(1, Math.min(60, Math.trunc(numeric)))
|
|
84
|
+
if (key === 'searchLimit') return Math.max(1, Math.min(100, Math.trunc(numeric)))
|
|
85
|
+
if (key === 'consolidateIntervalMs') return Math.max(60_000, Math.trunc(numeric))
|
|
86
|
+
if (key === 'injectRefreshMs') return Math.max(10_000, Math.trunc(numeric))
|
|
87
|
+
if (key === 'staleDays') return Math.max(1, Math.min(3650, Math.trunc(numeric)))
|
|
88
|
+
if (key === 'personaMinImportance' || key === 'workMinImportance') return Math.max(1, Math.min(5, Math.trunc(numeric)))
|
|
89
|
+
return fallback
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Read `<storeDir>/config.json` when it exists; a malformed file is ignored. */
|
|
93
|
+
function readConfigFile(storeDir, onWarning) {
|
|
94
|
+
const file = path.join(storeDir, 'config.json')
|
|
95
|
+
try {
|
|
96
|
+
const raw = fs.readFileSync(file, 'utf8')
|
|
97
|
+
const parsed = JSON.parse(raw)
|
|
98
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (error?.code !== 'ENOENT') onWarning?.(`ignoring unreadable ${file}: ${error?.message ?? error}`)
|
|
101
|
+
return {}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Resolve the effective settings.
|
|
107
|
+
*
|
|
108
|
+
* @param {object} rowConfig - configuration from the composition row.
|
|
109
|
+
* @param {(message: string) => void} [onWarning] - diagnostic sink.
|
|
110
|
+
* @returns {typeof DEFAULTS} the resolved settings.
|
|
111
|
+
*/
|
|
112
|
+
export function resolveSettings(rowConfig, onWarning) {
|
|
113
|
+
const base = {}
|
|
114
|
+
const rowStoreDir = typeof rowConfig?.storeDir === 'string' && rowConfig.storeDir.trim().length > 0
|
|
115
|
+
? path.resolve(rowConfig.storeDir.trim())
|
|
116
|
+
: DEFAULTS.storeDir
|
|
117
|
+
const fileConfig = readConfigFile(rowStoreDir, onWarning)
|
|
118
|
+
const merged = { ...DEFAULTS, ...fileConfig, ...(rowConfig ?? {}) }
|
|
119
|
+
for (const key of Object.keys(DEFAULTS)) base[key] = coerce(key, merged[key], DEFAULTS[key])
|
|
120
|
+
return base
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Write the effective settings next to the store, for inspection and debugging. */
|
|
124
|
+
export function writeEffectiveConfig(settings) {
|
|
125
|
+
try {
|
|
126
|
+
fs.mkdirSync(settings.storeDir, { recursive: true })
|
|
127
|
+
const file = path.join(settings.storeDir, 'effective-config.json')
|
|
128
|
+
fs.writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`, 'utf8')
|
|
129
|
+
return file
|
|
130
|
+
} catch {
|
|
131
|
+
return undefined
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Periodic memory consolidation.
|
|
3
|
+
*
|
|
4
|
+
* Runs on a timer and after a threshold of log growth. Four passes, each limited
|
|
5
|
+
* to what can be decided without guessing:
|
|
6
|
+
*
|
|
7
|
+
* 1. **Deduplicate** — near-identical records of the same kind and partition are
|
|
8
|
+
* merged; the survivor keeps the longer text and the union of the tags.
|
|
9
|
+
* 2. **Resolve conflicts** — for `preference` and `decision` records, a newer
|
|
10
|
+
* entry with a high but not identical overlap supersedes the older one, so a
|
|
11
|
+
* revised decision wins without deleting the history behind it.
|
|
12
|
+
* 3. **Archive stale entries** — old, never-used, low-importance `note`/`fact`
|
|
13
|
+
* records leave the active set but stay recallable.
|
|
14
|
+
* 4. **Enforce the size cap** — when the store exceeds `maxRecords`, the
|
|
15
|
+
* lowest-value records are archived first.
|
|
16
|
+
*
|
|
17
|
+
* @module dsh-long-term-memory/consolidate
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { normalizeTags, recordLabel } from './records.js'
|
|
21
|
+
import { containment, tokenSet } from './retrieval.js'
|
|
22
|
+
import { normalizeText } from './util.js'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Containment at which two same-kind records are the same statement.
|
|
26
|
+
* Containment rather than Jaccard: a restated memory that adds one qualifier is
|
|
27
|
+
* still the same memory, and Jaccard would score it as unrelated.
|
|
28
|
+
*/
|
|
29
|
+
const MERGE_THRESHOLD = 0.95
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Containment at which a newer `preference`/`decision` replaces an older one.
|
|
33
|
+
* Deliberately conservative — distinct preferences often share most vocabulary,
|
|
34
|
+
* and wrongly superseding a still-valid preference is worse than leaving a stale
|
|
35
|
+
* one for the agent to correct explicitly with `memory_update`.
|
|
36
|
+
*/
|
|
37
|
+
const SUPERSEDE_THRESHOLD = 0.85
|
|
38
|
+
|
|
39
|
+
/** Kinds whose later statement should win over an earlier one. */
|
|
40
|
+
const SUPERSEDING_KINDS = new Set(['preference', 'decision'])
|
|
41
|
+
|
|
42
|
+
/** Value score used when the store must shed records. */
|
|
43
|
+
function retentionScore(record, reference) {
|
|
44
|
+
const importance = Number(record.importance) || 3
|
|
45
|
+
const usage = Math.log(1 + (Number(record.useCount) || 0))
|
|
46
|
+
const ageDays = Math.max(0, (reference - (record.updatedAt ?? 0)) / 86_400_000)
|
|
47
|
+
const recency = Math.exp(-ageDays / 240)
|
|
48
|
+
return importance + usage * 1.5 + recency
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Run every consolidation pass.
|
|
53
|
+
*
|
|
54
|
+
* @param {object} store - the memory store.
|
|
55
|
+
* @param {object} settings - resolved settings (`maxRecords`, `staleDays`).
|
|
56
|
+
* @returns {object} a summary of what changed.
|
|
57
|
+
*/
|
|
58
|
+
export function consolidate(store, settings) {
|
|
59
|
+
const reference = Date.now()
|
|
60
|
+
const summary = {
|
|
61
|
+
merged: 0,
|
|
62
|
+
superseded: 0,
|
|
63
|
+
archived: 0,
|
|
64
|
+
trimmed: 0,
|
|
65
|
+
recordsBefore: store.records.size,
|
|
66
|
+
recordsAfter: store.records.size,
|
|
67
|
+
compacted: false,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Pass 1 + 2: deduplicate and resolve conflicts, oldest first so the newest
|
|
71
|
+
// statement in a group survives.
|
|
72
|
+
const ordered = store.all().sort((left, right) => (left.updatedAt ?? 0) - (right.updatedAt ?? 0))
|
|
73
|
+
const consumed = new Set()
|
|
74
|
+
for (const record of ordered) {
|
|
75
|
+
if (consumed.has(record.id)) continue
|
|
76
|
+
if (record.status === 'archived' || record.status === 'superseded' || record.status === 'dropped') continue
|
|
77
|
+
const recordTokens = tokenSet(`${record.title ?? ''} ${record.text ?? ''}`)
|
|
78
|
+
if (recordTokens.size === 0) continue
|
|
79
|
+
for (const other of ordered) {
|
|
80
|
+
if (other.id === record.id || consumed.has(other.id)) continue
|
|
81
|
+
if (other.kind !== record.kind || other.scope !== record.scope) continue
|
|
82
|
+
if (other.scope === 'workspace' && other.workspaceKey !== record.workspaceKey) continue
|
|
83
|
+
if (other.status === 'archived' || other.status === 'superseded' || other.status === 'dropped') continue
|
|
84
|
+
const overlap = containment(recordTokens, tokenSet(`${other.title ?? ''} ${other.text ?? ''}`))
|
|
85
|
+
const newer = (other.updatedAt ?? 0) > (record.updatedAt ?? 0) ? other : record
|
|
86
|
+
const older = newer === other ? record : other
|
|
87
|
+
if (overlap >= MERGE_THRESHOLD) {
|
|
88
|
+
store.update(newer.id, {
|
|
89
|
+
text: (other.text ?? '').length > (record.text ?? '').length ? other.text : record.text,
|
|
90
|
+
title: recordLabel({ ...newer, text: (other.text ?? '').length > (record.text ?? '').length ? other.text : record.text }),
|
|
91
|
+
tags: normalizeTags([...(record.tags ?? []), ...(other.tags ?? [])]),
|
|
92
|
+
importance: Math.max(Number(record.importance) || 3, Number(other.importance) || 3),
|
|
93
|
+
useCount: (Number(record.useCount) || 0) + (Number(other.useCount) || 0),
|
|
94
|
+
})
|
|
95
|
+
store.update(older.id, { status: 'superseded', mergedInto: newer.id, supersedes: null })
|
|
96
|
+
consumed.add(older.id)
|
|
97
|
+
summary.merged += 1
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
if (SUPERSEDING_KINDS.has(record.kind) && overlap >= SUPERSEDE_THRESHOLD) {
|
|
101
|
+
store.update(older.id, { status: 'superseded', supersedes: null, mergedInto: null })
|
|
102
|
+
store.update(newer.id, { supersedes: older.id })
|
|
103
|
+
consumed.add(older.id)
|
|
104
|
+
summary.superseded += 1
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Pass 3: archive stale, unused, low-value trivia.
|
|
110
|
+
const staleMs = Math.max(1, Number(settings.staleDays) || 180) * 86_400_000
|
|
111
|
+
for (const record of store.all()) {
|
|
112
|
+
if (record.status !== 'active') continue
|
|
113
|
+
if (record.kind !== 'note' && record.kind !== 'fact') continue
|
|
114
|
+
if ((Number(record.useCount) || 0) > 0) continue
|
|
115
|
+
if ((Number(record.importance) || 3) > 2) continue
|
|
116
|
+
if (reference - (record.updatedAt ?? 0) < staleMs) continue
|
|
117
|
+
store.update(record.id, { status: 'archived' })
|
|
118
|
+
summary.archived += 1
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Pass 3b: a finished task is history, not work. Task capture writes one record
|
|
122
|
+
// per todo item in every session, so closed items would otherwise accumulate
|
|
123
|
+
// forever and crowd `memory_search` results. Archive them once resuming them no
|
|
124
|
+
// longer means anything.
|
|
125
|
+
for (const record of store.all()) {
|
|
126
|
+
if (record.kind !== 'task') continue
|
|
127
|
+
if (record.status !== 'done' && record.status !== 'dropped') continue
|
|
128
|
+
if (reference - (record.updatedAt ?? 0) < staleMs) continue
|
|
129
|
+
store.update(record.id, { status: 'archived' })
|
|
130
|
+
summary.archived += 1
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Pass 4: enforce the configured cap by archiving the least valuable first.
|
|
134
|
+
const maxRecords = Math.max(50, Number(settings.maxRecords) || 5000)
|
|
135
|
+
const live = store.all().filter(record => record.status !== 'archived' && record.status !== 'superseded' && record.status !== 'dropped')
|
|
136
|
+
if (live.length > maxRecords) {
|
|
137
|
+
const victims = live
|
|
138
|
+
.sort((left, right) => retentionScore(left, reference) - retentionScore(right, reference))
|
|
139
|
+
.slice(0, live.length - maxRecords)
|
|
140
|
+
for (const victim of victims) {
|
|
141
|
+
store.update(victim.id, { status: 'archived' })
|
|
142
|
+
summary.trimmed += 1
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const compacted = store.compact(true)
|
|
147
|
+
summary.compacted = compacted.compacted === true
|
|
148
|
+
summary.recordsAfter = store.records.size
|
|
149
|
+
store.lastConsolidatedAt = reference
|
|
150
|
+
return summary
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Whether enough time has passed since the last consolidation. */
|
|
154
|
+
export function dueForConsolidation(store, settings) {
|
|
155
|
+
const interval = Math.max(60_000, Number(settings.consolidateIntervalMs) || 21_600_000)
|
|
156
|
+
return Date.now() - (store.lastConsolidatedAt || 0) >= interval
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Normalized text of a record, exposed for tool-side duplicate checks. */
|
|
160
|
+
export function recordSignature(record) {
|
|
161
|
+
return normalizeText(`${record.kind}|${record.scope}|${record.workspaceKey ?? '-'}|${record.text}`)
|
|
162
|
+
}
|
package/lib/dashboard.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dashboard snapshot: one JSON document describing the whole memory state.
|
|
3
|
+
*
|
|
4
|
+
* The Web UI polls this through a Host route. It is deliberately a *snapshot*
|
|
5
|
+
* rather than a diff stream: the client compares consecutive snapshots to
|
|
6
|
+
* highlight what changed, which keeps the Host stateless and makes a missed poll
|
|
7
|
+
* harmless.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-long-term-memory/dashboard
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { DOMAINS } from './domains.js'
|
|
13
|
+
import { buildProfile } from './profile.js'
|
|
14
|
+
import { normalizeDomain } from './domains.js'
|
|
15
|
+
|
|
16
|
+
/** Rows kept in the "recent changes" feed. */
|
|
17
|
+
const RECENT_LIMIT = 20
|
|
18
|
+
|
|
19
|
+
/** One recent record, projected for display. */
|
|
20
|
+
function recentRow(record) {
|
|
21
|
+
return {
|
|
22
|
+
id: record.id,
|
|
23
|
+
kind: record.kind ?? 'note',
|
|
24
|
+
layer: record.layer ?? 'persona',
|
|
25
|
+
domain: record.domain ?? null,
|
|
26
|
+
facet: record.facet ?? null,
|
|
27
|
+
status: record.status ?? 'active',
|
|
28
|
+
text: String(record.text ?? '').slice(0, 400),
|
|
29
|
+
importance: Number(record.importance) || 3,
|
|
30
|
+
pinned: record.pinned === true,
|
|
31
|
+
updatedAt: record.updatedAt ?? 0,
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** One task, projected for display. */
|
|
36
|
+
function taskRow(record) {
|
|
37
|
+
return {
|
|
38
|
+
id: record.id,
|
|
39
|
+
text: String(record.text ?? '').slice(0, 300),
|
|
40
|
+
status: record.status,
|
|
41
|
+
workspace: record.workspace ?? null,
|
|
42
|
+
updatedAt: record.updatedAt ?? 0,
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Build the dashboard snapshot.
|
|
48
|
+
*
|
|
49
|
+
* @param {object} store - the memory store.
|
|
50
|
+
* @param {object} settings - resolved settings.
|
|
51
|
+
* @param {object} [options] - snapshot options.
|
|
52
|
+
* @param {number} [options.recentLimit] - recent rows to include.
|
|
53
|
+
* @returns {object} a JSON-serializable snapshot.
|
|
54
|
+
*/
|
|
55
|
+
export function buildSnapshot(store, settings, options = {}) {
|
|
56
|
+
const recentLimit = Math.max(1, Math.min(100, Number(options.recentLimit) || RECENT_LIMIT))
|
|
57
|
+
const stats = store.stats()
|
|
58
|
+
|
|
59
|
+
const persona = buildProfile(store, { layer: 'persona', settings, maxChars: 4000 })
|
|
60
|
+
const work = []
|
|
61
|
+
for (const domain of DOMAINS) {
|
|
62
|
+
const profile = buildProfile(store, { layer: 'work', domain, settings, maxChars: 4000 })
|
|
63
|
+
if (profile.count === 0) continue
|
|
64
|
+
work.push({ domain, count: profile.count, facets: profile.facets, entries: profile.entries })
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const records = store.all()
|
|
68
|
+
const tasks = records
|
|
69
|
+
.filter(record => record.kind === 'task' && (record.status === 'open' || record.status === 'blocked'))
|
|
70
|
+
.sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0))
|
|
71
|
+
.slice(0, 50)
|
|
72
|
+
.map(taskRow)
|
|
73
|
+
|
|
74
|
+
const recent = [...records]
|
|
75
|
+
.sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0))
|
|
76
|
+
.slice(0, recentLimit)
|
|
77
|
+
.map(recentRow)
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
generatedAt: Date.now(),
|
|
81
|
+
storeDir: store.dir,
|
|
82
|
+
records: stats.records,
|
|
83
|
+
logLines: stats.logLines,
|
|
84
|
+
corruptLines: stats.corruptLines,
|
|
85
|
+
approxBytes: stats.approxBytes,
|
|
86
|
+
byStatus: stats.byStatus,
|
|
87
|
+
byKind: stats.byKind,
|
|
88
|
+
byScope: stats.byScope,
|
|
89
|
+
lastCompactedAt: stats.lastCompactedAt,
|
|
90
|
+
lastConsolidatedAt: stats.lastConsolidatedAt,
|
|
91
|
+
error: stats.error,
|
|
92
|
+
persona: { count: persona.count, facets: persona.facets, entries: persona.entries },
|
|
93
|
+
work,
|
|
94
|
+
tasks,
|
|
95
|
+
recent,
|
|
96
|
+
domains: DOMAINS,
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Normalize a domain query parameter, exported for the route handler. */
|
|
101
|
+
export { normalizeDomain }
|
package/lib/domains.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Domain and facet vocabulary for the profile layers.
|
|
3
|
+
*
|
|
4
|
+
* A *layer* answers "whose knowledge is this": the person (`persona`), a field of
|
|
5
|
+
* work (`work`), a project (`project`), or a piece of work in flight
|
|
6
|
+
* (`episodic`). A *facet* answers "which aspect of that layer does it describe",
|
|
7
|
+
* and is what turns a pile of facts into a readable profile.
|
|
8
|
+
*
|
|
9
|
+
* Domains are deliberately coarse. A profile that covers six items is useful; one
|
|
10
|
+
* that covers one item per sub-speciality is noise. Splitting a domain is a
|
|
11
|
+
* configuration change, not a schema change.
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-long-term-memory/domains
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Coarse work domains a work profile can be built for. */
|
|
17
|
+
export const DOMAINS = ['development', 'data', 'ops-ci', 'design', 'product', 'writing', 'general']
|
|
18
|
+
|
|
19
|
+
/** Facets of the personal profile, in display order. */
|
|
20
|
+
export const PERSONA_FACETS = ['identity', 'communication', 'values', 'constraints', 'goals', 'working-style']
|
|
21
|
+
|
|
22
|
+
/** Facets of a work profile, in display order. */
|
|
23
|
+
export const WORK_FACETS = ['stack', 'conventions', 'quality', 'workflow', 'gotchas', 'decisions']
|
|
24
|
+
|
|
25
|
+
/** Human-facing label for one facet. */
|
|
26
|
+
export const FACET_LABELS = {
|
|
27
|
+
identity: 'identity',
|
|
28
|
+
communication: 'communication',
|
|
29
|
+
values: 'values and tradeoffs',
|
|
30
|
+
constraints: 'hard constraints',
|
|
31
|
+
goals: 'goals',
|
|
32
|
+
'working-style': 'working style',
|
|
33
|
+
stack: 'stack and tooling',
|
|
34
|
+
conventions: 'conventions',
|
|
35
|
+
quality: 'quality bar',
|
|
36
|
+
workflow: 'workflow',
|
|
37
|
+
gotchas: 'known pitfalls',
|
|
38
|
+
decisions: 'decisions',
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Path and name patterns that identify a work domain.
|
|
43
|
+
*
|
|
44
|
+
* Ordered: the first match wins, so the more specific patterns come first. These
|
|
45
|
+
* are heuristics on the *directory name*, not a classifier — a wrong guess only
|
|
46
|
+
* changes which work profile is injected, never what is stored.
|
|
47
|
+
*/
|
|
48
|
+
const DOMAIN_PATTERNS = [
|
|
49
|
+
{ domain: 'ops-ci', pattern: /(^|[\\/])(ops|infra|infrastructure|deploy|devops|ci|pipeline|k8s|terraform)([\\/]|$)/i },
|
|
50
|
+
{ domain: 'data', pattern: /(^|[\\/])(data|etl|analytics|warehouse|datalake|ml|models?|dataset)([\\/]|$)/i },
|
|
51
|
+
{ domain: 'design', pattern: /(^|[\\/])(design|ui-?kit|figma|theme|styles?|tokens)([\\/]|$)/i },
|
|
52
|
+
{ domain: 'product', pattern: /(^|[\\/])(product|prd|specs?|roadmap|requirements)([\\/]|$)/i },
|
|
53
|
+
{ domain: 'writing', pattern: /(^|[\\/])(docs?|writing|blog|content|articles?|posts?)([\\/]|$)/i },
|
|
54
|
+
{ domain: 'development', pattern: /(^|[\\/])(web|frontend|front-end|ui|app|client|api|backend|back-end|server|service|sdk|cli|mobile)([\\/]|$)/i },
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
/** Whether a value is one of the known domains. */
|
|
58
|
+
export function isDomain(value) {
|
|
59
|
+
return typeof value === 'string' && DOMAINS.includes(value)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Layers a record can belong to. */
|
|
63
|
+
export const LAYERS = ['persona', 'work', 'project', 'episodic']
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Wording that makes a fact about the person rather than about the machine.
|
|
67
|
+
*
|
|
68
|
+
* Only used to file a `fact` by default. Everything else is filed by kind, and
|
|
69
|
+
* every default can be overridden by an explicit `layer`.
|
|
70
|
+
*/
|
|
71
|
+
const PERSONAL_HINT = /\bi\b|\bmy\b|\bme\b|我是|我的|本人|我这|我习惯/i
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Which layer a record belongs to, from what is known about it.
|
|
75
|
+
*
|
|
76
|
+
* Kept here rather than in the record module so both the writer and the profile
|
|
77
|
+
* builder share one rule without a circular import.
|
|
78
|
+
*
|
|
79
|
+
* `capability` deliberately does **not** default to the persona: a statement
|
|
80
|
+
* about what the agent can do is not a statement about who the user is, and
|
|
81
|
+
* filing it under "identity" made the personal profile read like an inventory of
|
|
82
|
+
* the installation.
|
|
83
|
+
*/
|
|
84
|
+
export function inferLayer(kind, scope, domain, text = '') {
|
|
85
|
+
if (kind === 'task') return 'episodic'
|
|
86
|
+
if (kind === 'project') return 'project'
|
|
87
|
+
if (isDomain(domain)) return 'work'
|
|
88
|
+
if (kind === 'solution' || kind === 'decision' || kind === 'capability') return 'work'
|
|
89
|
+
if (kind === 'fact') return PERSONAL_HINT.test(String(text)) ? 'persona' : 'work'
|
|
90
|
+
if (scope === 'workspace') return 'project'
|
|
91
|
+
return 'persona'
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Coerce a domain to a known value, or `general`. */
|
|
95
|
+
export function normalizeDomain(value) {
|
|
96
|
+
return isDomain(value) ? value : 'general'
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Facet vocabulary of one layer. */
|
|
100
|
+
export function facetsOf(layer) {
|
|
101
|
+
return layer === 'work' ? WORK_FACETS : PERSONA_FACETS
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Coerce a facet to one valid for the layer, or `undefined` when unusable. */
|
|
105
|
+
export function normalizeFacet(layer, value) {
|
|
106
|
+
if (typeof value !== 'string') return undefined
|
|
107
|
+
const facet = value.trim().toLowerCase()
|
|
108
|
+
return facetsOf(layer).includes(facet) ? facet : undefined
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The facet a record belongs to when the caller did not choose one.
|
|
113
|
+
*
|
|
114
|
+
* Defaults follow the kind, which is the only signal every record has. A keyword
|
|
115
|
+
* pass then rescues the two facets whose vocabulary is unmistakable.
|
|
116
|
+
*/
|
|
117
|
+
export function defaultFacet(layer, kind, text = '') {
|
|
118
|
+
const fromText = inferFacetFromText(layer, text)
|
|
119
|
+
if (fromText !== undefined) return fromText
|
|
120
|
+
if (layer === 'work') {
|
|
121
|
+
switch (kind) {
|
|
122
|
+
case 'decision': return 'decisions'
|
|
123
|
+
case 'solution': return 'gotchas'
|
|
124
|
+
case 'capability':
|
|
125
|
+
case 'fact': return 'stack'
|
|
126
|
+
default: return 'conventions'
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
switch (kind) {
|
|
130
|
+
case 'capability': return 'identity'
|
|
131
|
+
case 'fact': return 'identity'
|
|
132
|
+
case 'decision': return 'values'
|
|
133
|
+
default: return 'working-style'
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Keyword hints strong enough to override the kind-based default. */
|
|
138
|
+
const FACET_HINTS = [
|
|
139
|
+
{ facet: 'communication', pattern: /\b(?:reply|respond|answer|language|chinese|english|tone|concise|verbose|format)\b|回复|沟通|中文|英文|语气|简洁|详细|格式/i },
|
|
140
|
+
{ facet: 'identity', pattern: /\b(?:my name|i am|i'm|my role|my job|i work)\b|我是|我的角色|我的职业|我的名字/i },
|
|
141
|
+
{ facet: 'goals', pattern: /\b(?:goal|objective|aim|plan to|want to achieve)\b|目标|计划|想要实现/i },
|
|
142
|
+
{ facet: 'constraints', pattern: /\b(?:must not|never|not allowed|cannot|forbidden|compliance|deadline)\b|不能|禁止|不允许|合规|期限/i },
|
|
143
|
+
]
|
|
144
|
+
|
|
145
|
+
/** Facet implied by wording, when the wording is unambiguous. */
|
|
146
|
+
export function inferFacetFromText(layer, text) {
|
|
147
|
+
const facets = facetsOf(layer)
|
|
148
|
+
for (const hint of FACET_HINTS) {
|
|
149
|
+
if (!facets.includes(hint.facet)) continue
|
|
150
|
+
if (hint.pattern.test(text)) return hint.facet
|
|
151
|
+
}
|
|
152
|
+
return undefined
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Infer the work domain of a directory.
|
|
157
|
+
*
|
|
158
|
+
* Order: explicit configuration patterns, then the built-in directory heuristics,
|
|
159
|
+
* then `general`. A configured pattern may be a regular expression source or a
|
|
160
|
+
* plain substring; a malformed pattern is ignored rather than throwing.
|
|
161
|
+
*
|
|
162
|
+
* @param {string|null} directory - absolute workspace directory.
|
|
163
|
+
* @param {object} settings - resolved settings (uses `domains`).
|
|
164
|
+
* @returns {string} one of {@link DOMAINS}.
|
|
165
|
+
*/
|
|
166
|
+
export function inferDomain(directory, settings) {
|
|
167
|
+
if (typeof directory !== 'string' || directory.length === 0) return 'general'
|
|
168
|
+
const normalized = directory.replace(/\\/g, '/')
|
|
169
|
+
const configured = Array.isArray(settings?.domains) ? settings.domains : []
|
|
170
|
+
for (const entry of configured) {
|
|
171
|
+
if (entry === null || typeof entry !== 'object') continue
|
|
172
|
+
if (!isDomain(entry.domain) || typeof entry.pattern !== 'string' || entry.pattern.length === 0) continue
|
|
173
|
+
let matched = false
|
|
174
|
+
try {
|
|
175
|
+
matched = new RegExp(entry.pattern, 'i').test(normalized)
|
|
176
|
+
} catch {
|
|
177
|
+
matched = normalized.toLowerCase().includes(entry.pattern.toLowerCase())
|
|
178
|
+
}
|
|
179
|
+
if (matched) return entry.domain
|
|
180
|
+
}
|
|
181
|
+
for (const candidate of DOMAIN_PATTERNS) {
|
|
182
|
+
if (candidate.pattern.test(normalized)) return candidate.domain
|
|
183
|
+
}
|
|
184
|
+
return 'general'
|
|
185
|
+
}
|