Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
164 lines (157 loc) · 5.96 KB
/
Copy pathindex.js
File metadata and controls
164 lines (157 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import z from '@deepseek-ai/schemastery'
import { resolveTrashPaths } from './lib/paths.js'
import { TrashStore } from './lib/store.js'
import { createEligibility } from './lib/eligibility.js'
import { createStateService } from './lib/state.js'
import { createTrashService } from './lib/trash-service.js'
import { createCleanupService } from './lib/cleanup.js'
import { createStorageStats } from './lib/storage.js'
import { createReferenceScanner } from './lib/references.js'
import { createReclaimService } from './lib/reclaim.js'
import { registerApi } from './lib/http.js'
/** Host services this plugin cannot work without. */
export const inject = ['sessionPersistence', 'webServer', 'connection', 'sessions', 'agents']
/** Validated plugin configuration; ordinary fields restart the plugin when changed. */
export const Config = z.object({
retentionDays: z.natural().min(1).max(3650).default(30).description('Days a trashed session is kept before automatic deletion.'),
sweepIntervalHours: z
.natural()
.min(1)
.max(168)
.default(6)
.description('Hours between automatic cleanup sweeps.'),
enableAutoCleanup: z.boolean().default(true).description('Automatically delete sessions past the retention period.'),
debug: z.boolean().default(false).description('Emit detailed trash diagnostics.'),
})
/**
* Build a plain diagnostics sink that never depends on the shape of the
* harness logger service.
*
* @param {import('@deepseek-ai/cordis').Context} ctx plugin context.
* @returns {{ info: Function, warn: Function, error: Function, debug: Function }} a prefixed diagnostics sink.
*/
function createLogger(ctx) {
const prefix = 'dsh-session-trash'
let sink = null
try {
const factory = /** @type {any} */ (ctx.get('logger'))
if (typeof factory === 'function') {
const instance = factory(prefix)
if (instance !== null && instance !== undefined && typeof instance.info === 'function') sink = instance
} else if (factory !== null && factory !== undefined && typeof factory.info === 'function') {
sink = factory
}
} catch {
sink = null
}
const emit = (level, args) => {
if (sink !== null && typeof sink[level] === 'function') {
sink[level](...args)
return
}
const method = level === 'debug' ? 'log' : level
console[method](`[${prefix}]`, ...args)
}
return {
info: (...args) => emit('info', args),
warn: (...args) => emit('warn', args),
error: (...args) => emit('error', args),
debug: (...args) => emit('debug', args),
}
}
/**
* Register the trash services, its state projection, the HTTP API, crash
* recovery, and the retention sweep.
*
* @param {import('@deepseek-ai/cordis').Context} ctx plugin context.
* @param {any} config validated plugin configuration.
* @returns {void}
*/
export function apply(ctx, config) {
const logger = createLogger(ctx)
const scoped = config.debug ? logger : { ...logger, debug: () => {} }
const paths = resolveTrashPaths()
const store = new TrashStore({ root: paths.root, logger: scoped })
const references = createReferenceScanner({ home: paths.home, logger: scoped })
const storageStats = createStorageStats({ ctx, home: paths.home, logger: scoped, references })
const eligibility = createEligibility({ ctx, store, logger: scoped })
const trashService = createTrashService({
ctx,
store,
eligibility,
config,
logger: scoped,
paths,
})
const reclaimService = createReclaimService({
ctx,
store,
trashService,
references,
paths,
logger: scoped,
})
const cleanupService = createCleanupService({
ctx,
trashService,
config,
logger: scoped,
})
const stateService = createStateService({
store,
config,
trashRootDisplay: paths.display,
nextSweepAt: () => cleanupService.nextSweepAt(),
cleanup: () => cleanupService.diagnostics(),
workspaceRegistry: () => ctx.get('workspaceRegistry'),
storageSnapshot: (entries) => storageStats.snapshot({ entries }),
})
ctx.effect(() => () => cleanupService.stop(), 'session-trash: cleanup disposal')
const ready = store
.init()
.then(async (summary) => {
logger.info(
`trash root ready at ${paths.display}; retention ${config.retentionDays}d, sweep every ${config.sweepIntervalHours}h; index ${summary.status}, ${store.entries().length} entries`,
)
try {
const recovery = await trashService.recover()
if (recovery.changed > 0) {
logger.info(
`startup recovery settled ${recovery.changed} entries (${recovery.completed} completed, ${recovery.rolledBack} rolled back, ${recovery.missing} missing)`,
)
}
} catch (error) {
logger.error(
`startup trash recovery failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
)
}
try {
const titles = await trashService.repairTitles()
if (titles.repaired > 0) {
logger.info(`recovered ${titles.repaired} conversation titles from the projection cache`)
}
} catch (error) {
logger.warn(
`startup title repair failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
)
}
try {
const swept = await trashService.sweepProjectionCache()
if (swept.removed > 0) {
logger.info(`swept ${swept.removed} stale projection-cache records`)
}
} catch (error) {
logger.warn(
`startup projection-cache sweep failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
)
}
cleanupService.start()
return summary
})
.catch((error) => {
logger.error(`trash root initialization failed at ${paths.display}: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`)
throw error
})
ready.catch(() => {})
registerApi({ ctx, eligibility, stateService, trashService, reclaimService, cleanupService, ready, config, logger: scoped })
}