humemory 0.2.5 → 0.2.6
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/CHANGELOG.md +6 -0
- package/dist/agent/maintenance-runner.d.ts +90 -0
- package/dist/agent/maintenance-runner.js +188 -0
- package/dist/agent/maintenance-state.d.ts +73 -0
- package/dist/agent/maintenance-state.js +108 -0
- package/dist/api/maintenance-routes.d.ts +25 -0
- package/dist/api/maintenance-routes.js +54 -0
- package/dist/api/server.js +47 -0
- package/dist/cli/index.js +52 -0
- package/package.json +3 -1
- package/scripts/maintenance-worker.ts +15 -29
package/CHANGELOG.md
CHANGED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One maintenance pass: pull in what the local agents wrote since last time,
|
|
3
|
+
* then drain the queue into memory.
|
|
4
|
+
*
|
|
5
|
+
* The pass has exactly one definition here, callable from two places:
|
|
6
|
+
* `scripts/maintenance-worker.ts` (a one-shot CLI run) and the long-lived API
|
|
7
|
+
* process (`startMaintenanceLoop`). It used to live only in the script, driven
|
|
8
|
+
* by a Windows scheduled task whose `cmd` action flashed a console window every
|
|
9
|
+
* 15 minutes; hosting it in the already-resident, windowless API process is what
|
|
10
|
+
* removed the flash.
|
|
11
|
+
*
|
|
12
|
+
* Every pass writes to the state file (src/agent/maintenance-state.ts) whether
|
|
13
|
+
* it succeeds or fails, so a loop that has silently stopped is detectable from
|
|
14
|
+
* the CLI and the API instead of being noticed weeks later.
|
|
15
|
+
*/
|
|
16
|
+
import type { LLMClient } from '../core/llm-generator.js';
|
|
17
|
+
import type { Clock } from '../core/clock.js';
|
|
18
|
+
import { type WorkerResult } from './maintenance-queue.js';
|
|
19
|
+
import { type CodexImportResult } from './codex-import.js';
|
|
20
|
+
export declare const DEFAULT_INTERVAL_MS: number;
|
|
21
|
+
export interface MaintenancePassOptions {
|
|
22
|
+
queueDir?: string;
|
|
23
|
+
dbPath?: string;
|
|
24
|
+
statePath?: string;
|
|
25
|
+
/** Days of codex rollouts to sweep in. `false` skips the codex import entirely. */
|
|
26
|
+
codexSinceDays?: number | false;
|
|
27
|
+
/** Overrides `$CODEX_HOME/sessions`; mainly a test seam. */
|
|
28
|
+
codexSessionsDir?: string;
|
|
29
|
+
client?: LLMClient;
|
|
30
|
+
llmTimeoutMs?: number;
|
|
31
|
+
maxJobs?: number;
|
|
32
|
+
clock?: Clock;
|
|
33
|
+
/** Recorded in the state file so two competing schedulers are visible. */
|
|
34
|
+
runner?: string;
|
|
35
|
+
}
|
|
36
|
+
export interface MaintenancePassResult {
|
|
37
|
+
codex?: CodexImportResult;
|
|
38
|
+
/** Set when the codex import failed; the queue is still drained regardless. */
|
|
39
|
+
codexError?: string;
|
|
40
|
+
worker: WorkerResult;
|
|
41
|
+
}
|
|
42
|
+
export declare function defaultQueueDir(): string;
|
|
43
|
+
export declare function defaultDbPath(): string;
|
|
44
|
+
export declare function defaultLlmTimeoutMs(): number;
|
|
45
|
+
export declare function configuredIntervalMs(): number;
|
|
46
|
+
/**
|
|
47
|
+
* The LLM the pass consolidates with. 'none' (the default) keeps consolidation
|
|
48
|
+
* deterministic and network-free; there is no API key on the production machine
|
|
49
|
+
* and none wanted, so 'codex' shells out to the logged-in CLI instead.
|
|
50
|
+
*/
|
|
51
|
+
export declare function resolveMaintenanceClient(timeoutMs?: number): Promise<LLMClient | undefined>;
|
|
52
|
+
/**
|
|
53
|
+
* Import, then drain, then record. A failing codex import is contained: a
|
|
54
|
+
* missing or unreadable codex must never stall the queue, which holds sessions
|
|
55
|
+
* from every other source.
|
|
56
|
+
*
|
|
57
|
+
* Throws only if the queue itself could not be drained — the caller records
|
|
58
|
+
* that failure and stays alive.
|
|
59
|
+
*/
|
|
60
|
+
export declare function runMaintenancePass(options?: MaintenancePassOptions): Promise<MaintenancePassResult>;
|
|
61
|
+
/** Minimal timer seam, so the loop is testable without waiting on wall time. */
|
|
62
|
+
export interface TimerLike {
|
|
63
|
+
setInterval(handler: () => void, ms: number): unknown;
|
|
64
|
+
clearInterval(handle: unknown): void;
|
|
65
|
+
}
|
|
66
|
+
export interface MaintenanceLoop {
|
|
67
|
+
/** Runs a pass now, outside the schedule. Resolves once it has finished. */
|
|
68
|
+
runNow(): Promise<void>;
|
|
69
|
+
stop(): void;
|
|
70
|
+
/** True while a pass is in flight — the next tick is suppressed until it clears. */
|
|
71
|
+
readonly busy: boolean;
|
|
72
|
+
}
|
|
73
|
+
export interface MaintenanceLoopOptions extends MaintenancePassOptions {
|
|
74
|
+
intervalMs?: number;
|
|
75
|
+
/** Run one pass immediately instead of waiting a full interval. */
|
|
76
|
+
runAtStart?: boolean;
|
|
77
|
+
timers?: TimerLike;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Run a pass every `intervalMs` inside the calling process. The API process is
|
|
81
|
+
* already resident and windowless, so hosting the loop there spawns nothing —
|
|
82
|
+
* which is the whole point of moving it off the Windows scheduler.
|
|
83
|
+
*
|
|
84
|
+
* Three properties this guarantees, each covered by a test:
|
|
85
|
+
* - passes never overlap, on top of the queue's own cross-process lock;
|
|
86
|
+
* - a throwing pass is contained and the loop keeps ticking, because the API
|
|
87
|
+
* must not die of a bad session transcript;
|
|
88
|
+
* - every pass, good or bad, lands in the state file.
|
|
89
|
+
*/
|
|
90
|
+
export declare function startMaintenanceLoop(options?: MaintenanceLoopOptions): MaintenanceLoop;
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One maintenance pass: pull in what the local agents wrote since last time,
|
|
3
|
+
* then drain the queue into memory.
|
|
4
|
+
*
|
|
5
|
+
* The pass has exactly one definition here, callable from two places:
|
|
6
|
+
* `scripts/maintenance-worker.ts` (a one-shot CLI run) and the long-lived API
|
|
7
|
+
* process (`startMaintenanceLoop`). It used to live only in the script, driven
|
|
8
|
+
* by a Windows scheduled task whose `cmd` action flashed a console window every
|
|
9
|
+
* 15 minutes; hosting it in the already-resident, windowless API process is what
|
|
10
|
+
* removed the flash.
|
|
11
|
+
*
|
|
12
|
+
* Every pass writes to the state file (src/agent/maintenance-state.ts) whether
|
|
13
|
+
* it succeeds or fails, so a loop that has silently stopped is detectable from
|
|
14
|
+
* the CLI and the API instead of being noticed weeks later.
|
|
15
|
+
*/
|
|
16
|
+
import { dirname, join } from 'path';
|
|
17
|
+
import { fileURLToPath } from 'url';
|
|
18
|
+
import { systemClock } from '../core/clock.js';
|
|
19
|
+
import { createCodexClient } from '../core/llm-cli-client.js';
|
|
20
|
+
import { processMaintenanceQueue } from './maintenance-queue.js';
|
|
21
|
+
import { importCodexRollouts, defaultCodexSessionsDir } from './codex-import.js';
|
|
22
|
+
import { defaultStatePath, recordMaintenanceRun } from './maintenance-state.js';
|
|
23
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
24
|
+
export const DEFAULT_INTERVAL_MS = 15 * 60 * 1000;
|
|
25
|
+
export function defaultQueueDir() {
|
|
26
|
+
return process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
|
|
27
|
+
}
|
|
28
|
+
export function defaultDbPath() {
|
|
29
|
+
return process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
|
|
30
|
+
}
|
|
31
|
+
export function defaultLlmTimeoutMs() {
|
|
32
|
+
return Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000);
|
|
33
|
+
}
|
|
34
|
+
export function configuredIntervalMs() {
|
|
35
|
+
const raw = Number(process.env.HUMEMORY_MAINTENANCE_INTERVAL_MS ?? DEFAULT_INTERVAL_MS);
|
|
36
|
+
return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_INTERVAL_MS;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The LLM the pass consolidates with. 'none' (the default) keeps consolidation
|
|
40
|
+
* deterministic and network-free; there is no API key on the production machine
|
|
41
|
+
* and none wanted, so 'codex' shells out to the logged-in CLI instead.
|
|
42
|
+
*/
|
|
43
|
+
export async function resolveMaintenanceClient(timeoutMs = defaultLlmTimeoutMs()) {
|
|
44
|
+
const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? 'none';
|
|
45
|
+
if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
|
|
46
|
+
const { default: Anthropic } = await import('@anthropic-ai/sdk');
|
|
47
|
+
return new Anthropic();
|
|
48
|
+
}
|
|
49
|
+
if (provider === 'codex') {
|
|
50
|
+
// No API key needed: the logged-in `codex` CLI answers instead. Slower than
|
|
51
|
+
// an SDK call (agent start-up), so it gets its own, larger budget.
|
|
52
|
+
return createCodexClient({ timeoutMs });
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Import, then drain, then record. A failing codex import is contained: a
|
|
58
|
+
* missing or unreadable codex must never stall the queue, which holds sessions
|
|
59
|
+
* from every other source.
|
|
60
|
+
*
|
|
61
|
+
* Throws only if the queue itself could not be drained — the caller records
|
|
62
|
+
* that failure and stays alive.
|
|
63
|
+
*/
|
|
64
|
+
export async function runMaintenancePass(options = {}) {
|
|
65
|
+
const clock = options.clock ?? systemClock;
|
|
66
|
+
const queueDir = options.queueDir ?? defaultQueueDir();
|
|
67
|
+
const dbPath = options.dbPath ?? defaultDbPath();
|
|
68
|
+
const statePath = options.statePath ?? defaultStatePath(queueDir);
|
|
69
|
+
const llmTimeoutMs = options.llmTimeoutMs ?? defaultLlmTimeoutMs();
|
|
70
|
+
const sinceDays = options.codexSinceDays ?? 1;
|
|
71
|
+
const startedAt = clock.now();
|
|
72
|
+
let codex;
|
|
73
|
+
let codexError;
|
|
74
|
+
if (sinceDays !== false) {
|
|
75
|
+
try {
|
|
76
|
+
codex = await importCodexRollouts({
|
|
77
|
+
queueDir,
|
|
78
|
+
sessionsDir: options.codexSessionsDir ?? defaultCodexSessionsDir(),
|
|
79
|
+
since: new Date(startedAt.getTime() - sinceDays * 24 * 60 * 60 * 1000),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
codexError = error.message;
|
|
84
|
+
console.error('[humemory] maintenance: codex import failed —', codexError);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
const worker = await processMaintenanceQueue({
|
|
89
|
+
queueDir,
|
|
90
|
+
dbPath,
|
|
91
|
+
client: options.client,
|
|
92
|
+
llmTimeoutMs,
|
|
93
|
+
maxJobs: options.maxJobs ?? Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
|
|
94
|
+
now: () => clock.now(),
|
|
95
|
+
});
|
|
96
|
+
// A pass where every job failed is not a healthy pass. The queue isolates
|
|
97
|
+
// jobs on purpose — a bad transcript must not stop the others — but that
|
|
98
|
+
// isolation also makes an infrastructure failure (unopenable database, full
|
|
99
|
+
// disk) look exactly like a batch of bad sessions, and after `maxAttempts`
|
|
100
|
+
// it quietly dead-letters everything. Recording it as a failure is what
|
|
101
|
+
// makes that case visible before the queue has drained itself into nothing.
|
|
102
|
+
const wholesaleFailure = worker.discovered > 0 && worker.processed === 0 && worker.failed > 0;
|
|
103
|
+
await recordMaintenanceRun({
|
|
104
|
+
path: statePath,
|
|
105
|
+
startedAt,
|
|
106
|
+
clock,
|
|
107
|
+
runner: options.runner,
|
|
108
|
+
error: wholesaleFailure
|
|
109
|
+
? new Error(`every job failed this pass (${worker.failed}/${worker.discovered}) — suspect the database or the disk, not the sessions`)
|
|
110
|
+
: undefined,
|
|
111
|
+
result: {
|
|
112
|
+
discovered: worker.discovered,
|
|
113
|
+
processed: worker.processed,
|
|
114
|
+
failed: worker.failed,
|
|
115
|
+
deadLettered: worker.deadLettered,
|
|
116
|
+
memoriesStored: worker.memoriesStored,
|
|
117
|
+
busy: worker.busy,
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
return { codex, codexError, worker };
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
await recordMaintenanceRun({ path: statePath, startedAt, clock, runner: options.runner, error });
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const REAL_TIMERS = {
|
|
128
|
+
setInterval: (handler, ms) => {
|
|
129
|
+
const handle = setInterval(handler, ms);
|
|
130
|
+
// Maintenance alone is no reason to hold the process alive.
|
|
131
|
+
if (typeof handle.unref === 'function') {
|
|
132
|
+
handle.unref();
|
|
133
|
+
}
|
|
134
|
+
return handle;
|
|
135
|
+
},
|
|
136
|
+
clearInterval: (handle) => clearInterval(handle),
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Run a pass every `intervalMs` inside the calling process. The API process is
|
|
140
|
+
* already resident and windowless, so hosting the loop there spawns nothing —
|
|
141
|
+
* which is the whole point of moving it off the Windows scheduler.
|
|
142
|
+
*
|
|
143
|
+
* Three properties this guarantees, each covered by a test:
|
|
144
|
+
* - passes never overlap, on top of the queue's own cross-process lock;
|
|
145
|
+
* - a throwing pass is contained and the loop keeps ticking, because the API
|
|
146
|
+
* must not die of a bad session transcript;
|
|
147
|
+
* - every pass, good or bad, lands in the state file.
|
|
148
|
+
*/
|
|
149
|
+
export function startMaintenanceLoop(options = {}) {
|
|
150
|
+
const intervalMs = options.intervalMs ?? configuredIntervalMs();
|
|
151
|
+
const timers = options.timers ?? REAL_TIMERS;
|
|
152
|
+
let running = false;
|
|
153
|
+
let stopped = false;
|
|
154
|
+
const pass = async () => {
|
|
155
|
+
if (running || stopped)
|
|
156
|
+
return;
|
|
157
|
+
running = true;
|
|
158
|
+
try {
|
|
159
|
+
const client = options.client ?? await resolveMaintenanceClient(options.llmTimeoutMs);
|
|
160
|
+
const { worker } = await runMaintenancePass({ ...options, client, runner: options.runner ?? 'api-loop' });
|
|
161
|
+
if (process.env.HUMEMORY_VERBOSE === '1' || worker.failed > 0) {
|
|
162
|
+
console.error(`[humemory] maintenance: ${worker.processed}/${worker.discovered} jobs, ` +
|
|
163
|
+
`${worker.memoriesStored} memories, ${worker.failed} failed, ${worker.deadLettered} dead-lettered`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
// Contained on purpose: a crashing pass must never take the API down.
|
|
168
|
+
// The failure is already in the state file, so it stays visible.
|
|
169
|
+
console.error('[humemory] maintenance pass failed —', error.message);
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
running = false;
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const handle = timers.setInterval(() => void pass(), intervalMs);
|
|
176
|
+
if (options.runAtStart)
|
|
177
|
+
void pass();
|
|
178
|
+
return {
|
|
179
|
+
runNow: pass,
|
|
180
|
+
get busy() {
|
|
181
|
+
return running;
|
|
182
|
+
},
|
|
183
|
+
stop() {
|
|
184
|
+
stopped = true;
|
|
185
|
+
timers.clearInterval(handle);
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable record of how maintenance is actually going.
|
|
3
|
+
*
|
|
4
|
+
* Without this, a stopped maintenance loop is invisible: the queue simply stops
|
|
5
|
+
* draining and nothing says so until someone notices memories are missing. The
|
|
6
|
+
* state file is the answer to "is consolidation still alive, and since when".
|
|
7
|
+
*
|
|
8
|
+
* It is a plain JSON file rather than a table on purpose. This is the health
|
|
9
|
+
* signal *about* the system, so it must not depend on the part of the system
|
|
10
|
+
* most likely to be broken — a locked or corrupt database still leaves a
|
|
11
|
+
* readable answer here. Writes are atomic (temp file + rename) so a crash
|
|
12
|
+
* mid-write cannot leave a truncated state behind.
|
|
13
|
+
*/
|
|
14
|
+
import type { Clock } from '../core/clock.js';
|
|
15
|
+
/** A pass is considered overdue at four intervals without a success. */
|
|
16
|
+
export declare const DEFAULT_STALE_AFTER_MS: number;
|
|
17
|
+
export interface MaintenanceState {
|
|
18
|
+
/** Start of the most recent pass, successful or not. */
|
|
19
|
+
lastRunAt?: string;
|
|
20
|
+
lastSuccessAt?: string;
|
|
21
|
+
lastDurationMs?: number;
|
|
22
|
+
/** Reset to 0 by any success — a non-zero value means the loop is degraded, not dead. */
|
|
23
|
+
consecutiveFailures: number;
|
|
24
|
+
/** Message only, never a stack: this is read back over the API. */
|
|
25
|
+
lastError?: string;
|
|
26
|
+
lastResult?: {
|
|
27
|
+
discovered: number;
|
|
28
|
+
processed: number;
|
|
29
|
+
failed: number;
|
|
30
|
+
deadLettered: number;
|
|
31
|
+
memoriesStored: number;
|
|
32
|
+
/** True when another worker held the lock — not a failure. */
|
|
33
|
+
busy: boolean;
|
|
34
|
+
};
|
|
35
|
+
/** Which process last wrote here, so two schedulers fighting is visible. */
|
|
36
|
+
lastRunner?: string;
|
|
37
|
+
}
|
|
38
|
+
export declare function defaultStatePath(queueDir: string): string;
|
|
39
|
+
/**
|
|
40
|
+
* Never throws: an absent file is a fresh install, and a corrupt one must not
|
|
41
|
+
* take down the caller that is merely asking for a status.
|
|
42
|
+
*/
|
|
43
|
+
export declare function readMaintenanceState(path: string): Promise<MaintenanceState>;
|
|
44
|
+
export interface RecordRunOptions {
|
|
45
|
+
path: string;
|
|
46
|
+
startedAt: Date;
|
|
47
|
+
clock?: Clock;
|
|
48
|
+
runner?: string;
|
|
49
|
+
result?: MaintenanceState['lastResult'];
|
|
50
|
+
error?: unknown;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Fold one pass into the state file. Recording is best-effort by design: a
|
|
54
|
+
* read-only disk must degrade observability, never stop consolidation.
|
|
55
|
+
*/
|
|
56
|
+
export declare function recordMaintenanceRun(options: RecordRunOptions): Promise<MaintenanceState>;
|
|
57
|
+
export interface MaintenanceHealth {
|
|
58
|
+
/** No success ever, or the last one is older than the staleness budget. */
|
|
59
|
+
stale: boolean;
|
|
60
|
+
/** Milliseconds since the last success; undefined when there has never been one. */
|
|
61
|
+
ageMs?: number;
|
|
62
|
+
consecutiveFailures: number;
|
|
63
|
+
lastSuccessAt?: string;
|
|
64
|
+
lastRunAt?: string;
|
|
65
|
+
lastError?: string;
|
|
66
|
+
lastResult?: MaintenanceState['lastResult'];
|
|
67
|
+
/** One line a human can act on. */
|
|
68
|
+
summary: string;
|
|
69
|
+
}
|
|
70
|
+
export declare function assessMaintenance(state: MaintenanceState, options?: {
|
|
71
|
+
staleAfterMs?: number;
|
|
72
|
+
clock?: Clock;
|
|
73
|
+
}): MaintenanceHealth;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable record of how maintenance is actually going.
|
|
3
|
+
*
|
|
4
|
+
* Without this, a stopped maintenance loop is invisible: the queue simply stops
|
|
5
|
+
* draining and nothing says so until someone notices memories are missing. The
|
|
6
|
+
* state file is the answer to "is consolidation still alive, and since when".
|
|
7
|
+
*
|
|
8
|
+
* It is a plain JSON file rather than a table on purpose. This is the health
|
|
9
|
+
* signal *about* the system, so it must not depend on the part of the system
|
|
10
|
+
* most likely to be broken — a locked or corrupt database still leaves a
|
|
11
|
+
* readable answer here. Writes are atomic (temp file + rename) so a crash
|
|
12
|
+
* mid-write cannot leave a truncated state behind.
|
|
13
|
+
*/
|
|
14
|
+
import { readFile, rename, writeFile, mkdir } from 'fs/promises';
|
|
15
|
+
import { dirname, join } from 'path';
|
|
16
|
+
import { systemClock } from '../core/clock.js';
|
|
17
|
+
/** A pass is considered overdue at four intervals without a success. */
|
|
18
|
+
export const DEFAULT_STALE_AFTER_MS = 60 * 60 * 1000;
|
|
19
|
+
const EMPTY = { consecutiveFailures: 0 };
|
|
20
|
+
export function defaultStatePath(queueDir) {
|
|
21
|
+
return join(dirname(queueDir), 'maintenance-state.json');
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Never throws: an absent file is a fresh install, and a corrupt one must not
|
|
25
|
+
* take down the caller that is merely asking for a status.
|
|
26
|
+
*/
|
|
27
|
+
export async function readMaintenanceState(path) {
|
|
28
|
+
try {
|
|
29
|
+
const parsed = JSON.parse(await readFile(path, 'utf-8'));
|
|
30
|
+
if (!parsed || typeof parsed !== 'object')
|
|
31
|
+
return { ...EMPTY };
|
|
32
|
+
return { ...EMPTY, ...parsed };
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return { ...EMPTY };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async function writeAtomic(path, state) {
|
|
39
|
+
await mkdir(dirname(path), { recursive: true });
|
|
40
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
41
|
+
await writeFile(tmp, JSON.stringify(state, null, 2), 'utf-8');
|
|
42
|
+
await rename(tmp, path);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Fold one pass into the state file. Recording is best-effort by design: a
|
|
46
|
+
* read-only disk must degrade observability, never stop consolidation.
|
|
47
|
+
*/
|
|
48
|
+
export async function recordMaintenanceRun(options) {
|
|
49
|
+
const clock = options.clock ?? systemClock;
|
|
50
|
+
const previous = await readMaintenanceState(options.path);
|
|
51
|
+
const finishedAt = clock.now();
|
|
52
|
+
const succeeded = options.error === undefined;
|
|
53
|
+
const next = {
|
|
54
|
+
...previous,
|
|
55
|
+
lastRunAt: options.startedAt.toISOString(),
|
|
56
|
+
lastDurationMs: Math.max(0, finishedAt.getTime() - options.startedAt.getTime()),
|
|
57
|
+
consecutiveFailures: succeeded ? 0 : previous.consecutiveFailures + 1,
|
|
58
|
+
lastRunner: options.runner ?? previous.lastRunner,
|
|
59
|
+
};
|
|
60
|
+
// Counts are recorded either way: a pass that failed wholesale still says how
|
|
61
|
+
// many jobs it saw, which is the first thing to look at when diagnosing it.
|
|
62
|
+
if (options.result)
|
|
63
|
+
next.lastResult = options.result;
|
|
64
|
+
if (succeeded) {
|
|
65
|
+
next.lastSuccessAt = finishedAt.toISOString();
|
|
66
|
+
delete next.lastError;
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
next.lastError = options.error instanceof Error ? options.error.message : String(options.error);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
await writeAtomic(options.path, next);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
console.error('[humemory] maintenance: could not record state —', error.message);
|
|
76
|
+
}
|
|
77
|
+
return next;
|
|
78
|
+
}
|
|
79
|
+
export function assessMaintenance(state, options = {}) {
|
|
80
|
+
const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
|
|
81
|
+
const now = (options.clock ?? systemClock).now().getTime();
|
|
82
|
+
const lastSuccess = state.lastSuccessAt ? Date.parse(state.lastSuccessAt) : undefined;
|
|
83
|
+
const ageMs = lastSuccess !== undefined && Number.isFinite(lastSuccess) ? now - lastSuccess : undefined;
|
|
84
|
+
const stale = ageMs === undefined || ageMs > staleAfterMs;
|
|
85
|
+
let summary;
|
|
86
|
+
if (ageMs === undefined) {
|
|
87
|
+
summary = 'no maintenance pass has ever succeeded';
|
|
88
|
+
}
|
|
89
|
+
else if (stale) {
|
|
90
|
+
summary = `last success ${Math.round(ageMs / 60_000)} min ago — over the ${Math.round(staleAfterMs / 60_000)} min budget`;
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
summary = `healthy — last success ${Math.round(ageMs / 60_000)} min ago`;
|
|
94
|
+
}
|
|
95
|
+
if (state.consecutiveFailures > 0) {
|
|
96
|
+
summary += `, ${state.consecutiveFailures} consecutive failure(s)`;
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
stale,
|
|
100
|
+
ageMs,
|
|
101
|
+
consecutiveFailures: state.consecutiveFailures,
|
|
102
|
+
lastSuccessAt: state.lastSuccessAt,
|
|
103
|
+
lastRunAt: state.lastRunAt,
|
|
104
|
+
lastError: state.lastError,
|
|
105
|
+
lastResult: state.lastResult,
|
|
106
|
+
summary,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP surface for maintenance health (same testable-sub-router pattern as
|
|
3
|
+
* dream-routes.ts: every path is a parameter, no production files in tests).
|
|
4
|
+
*
|
|
5
|
+
* These routes sit behind the API token like every other data route. `/health`
|
|
6
|
+
* deliberately stays coarse and public — the watchdog only needs liveness, and
|
|
7
|
+
* `lastError` is internal detail that has no business on an unauthenticated
|
|
8
|
+
* endpoint (SECURITY_AUDIT.md L-01).
|
|
9
|
+
*/
|
|
10
|
+
import { Hono } from 'hono';
|
|
11
|
+
export interface MaintenanceLoopHandle {
|
|
12
|
+
runNow(): Promise<void>;
|
|
13
|
+
readonly busy: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface MaintenanceRoutesOptions {
|
|
16
|
+
statePath: string;
|
|
17
|
+
staleAfterMs?: number;
|
|
18
|
+
/**
|
|
19
|
+
* Resolves the loop this process hosts, or undefined when an external
|
|
20
|
+
* scheduler drives maintenance instead. A getter rather than a value because
|
|
21
|
+
* the server binds the routes before it decides to start the loop.
|
|
22
|
+
*/
|
|
23
|
+
loop?: () => MaintenanceLoopHandle | undefined;
|
|
24
|
+
}
|
|
25
|
+
export declare function createMaintenanceRoutes(options: MaintenanceRoutesOptions): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP surface for maintenance health (same testable-sub-router pattern as
|
|
3
|
+
* dream-routes.ts: every path is a parameter, no production files in tests).
|
|
4
|
+
*
|
|
5
|
+
* These routes sit behind the API token like every other data route. `/health`
|
|
6
|
+
* deliberately stays coarse and public — the watchdog only needs liveness, and
|
|
7
|
+
* `lastError` is internal detail that has no business on an unauthenticated
|
|
8
|
+
* endpoint (SECURITY_AUDIT.md L-01).
|
|
9
|
+
*/
|
|
10
|
+
import { Hono } from 'hono';
|
|
11
|
+
import { assessMaintenance, readMaintenanceState, DEFAULT_STALE_AFTER_MS } from '../agent/maintenance-state.js';
|
|
12
|
+
import { serverErrorBody } from './errors.js';
|
|
13
|
+
export function createMaintenanceRoutes(options) {
|
|
14
|
+
const app = new Hono();
|
|
15
|
+
const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
|
|
16
|
+
app.get('/maintenance/status', async (c) => {
|
|
17
|
+
try {
|
|
18
|
+
const state = await readMaintenanceState(options.statePath);
|
|
19
|
+
const health = assessMaintenance(state, { staleAfterMs });
|
|
20
|
+
return c.json({
|
|
21
|
+
success: true,
|
|
22
|
+
maintenance: {
|
|
23
|
+
...health,
|
|
24
|
+
hostedHere: options.loop?.() !== undefined,
|
|
25
|
+
running: options.loop?.()?.busy ?? false,
|
|
26
|
+
staleAfterMs,
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
return c.json(serverErrorBody('maintenance status', error), 500);
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
// Force a pass — the dashboard's "consolidate now", and the escape hatch when
|
|
35
|
+
// the schedule is known to have missed a window.
|
|
36
|
+
app.post('/maintenance/run', async (c) => {
|
|
37
|
+
const loop = options.loop?.();
|
|
38
|
+
if (!loop) {
|
|
39
|
+
return c.json({ success: false, error: 'No maintenance loop in this process' }, 409);
|
|
40
|
+
}
|
|
41
|
+
if (loop.busy) {
|
|
42
|
+
return c.json({ success: false, error: 'A maintenance pass is already running' }, 409);
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
await loop.runNow();
|
|
46
|
+
const state = await readMaintenanceState(options.statePath);
|
|
47
|
+
return c.json({ success: true, maintenance: assessMaintenance(state, { staleAfterMs }) });
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
return c.json(serverErrorBody('maintenance run', error), 500);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
return app;
|
|
54
|
+
}
|
package/dist/api/server.js
CHANGED
|
@@ -41,6 +41,9 @@ import { createIntentionRoutes } from './intentions-routes.js';
|
|
|
41
41
|
import { createMemoryRoutes } from './memory-routes.js';
|
|
42
42
|
import { createDreamRoutes } from './dream-routes.js';
|
|
43
43
|
import { createScriptRoutes } from './scripts-routes.js';
|
|
44
|
+
import { createMaintenanceRoutes } from './maintenance-routes.js';
|
|
45
|
+
import { defaultStatePath } from '../agent/maintenance-state.js';
|
|
46
|
+
import { startMaintenanceLoop, configuredIntervalMs, } from '../agent/maintenance-runner.js';
|
|
44
47
|
import { join, dirname, resolve, sep } from 'path';
|
|
45
48
|
import { fileURLToPath } from 'url';
|
|
46
49
|
import { readFileSync } from 'fs';
|
|
@@ -64,6 +67,11 @@ function safeJoin(baseDir, ...segments) {
|
|
|
64
67
|
const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
|
|
65
68
|
const store = new SQLiteStore(DB_PATH);
|
|
66
69
|
const PUBLIC_DIR = join(__dirname, '../../public');
|
|
70
|
+
const QUEUE_DIR = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
|
|
71
|
+
const MAINTENANCE_STATE_PATH = defaultStatePath(QUEUE_DIR);
|
|
72
|
+
// Assigned only when this process hosts the loop; the routes read it to report
|
|
73
|
+
// whether maintenance lives here and whether a pass is in flight right now.
|
|
74
|
+
let maintenanceLoop;
|
|
67
75
|
// Configure CORS securely (allow localhost for development, restrict in production)
|
|
68
76
|
const allowedOrigins = process.env.NODE_ENV === 'production'
|
|
69
77
|
? (process.env.CORS_ORIGINS || 'http://localhost:3456').split(',')
|
|
@@ -182,6 +190,12 @@ app.route('/', createIntentionRoutes(store));
|
|
|
182
190
|
app.route('/', createDreamRoutes(store));
|
|
183
191
|
// === COGNITIVE SCRIPTS (Phase 8.3) ===
|
|
184
192
|
app.route('/', createScriptRoutes(store));
|
|
193
|
+
// === MAINTENANCE HEALTH ===
|
|
194
|
+
// Behind the token like every other data route: `lastError` is internal detail.
|
|
195
|
+
app.route('/', createMaintenanceRoutes({
|
|
196
|
+
statePath: MAINTENANCE_STATE_PATH,
|
|
197
|
+
loop: () => maintenanceLoop,
|
|
198
|
+
}));
|
|
185
199
|
// === HEALTH ===
|
|
186
200
|
app.get('/health', (c) => {
|
|
187
201
|
return c.json({ status: 'ok', timestamp: new Date().toISOString() });
|
|
@@ -207,4 +221,37 @@ if (import.meta.main) {
|
|
|
207
221
|
console.warn('⚠️ HUMEMORY_API_TOKEN not set — data routes are unauthenticated (loopback only).');
|
|
208
222
|
}
|
|
209
223
|
serve({ fetch: app.fetch, port, hostname });
|
|
224
|
+
// Maintenance runs here rather than in an external scheduler: on Windows a
|
|
225
|
+
// scheduled task under an interactive token flashes a console window at every
|
|
226
|
+
// tick, and running it "whether the user is logged on or not" needs elevation
|
|
227
|
+
// this machine does not grant. This process is already resident and hidden.
|
|
228
|
+
// HUMEMORY_MAINTENANCE_INTERVAL_MS=0 hands the job back to a scheduler; the
|
|
229
|
+
// state file and /maintenance/status stay meaningful either way.
|
|
230
|
+
const maintenanceInterval = configuredIntervalMs();
|
|
231
|
+
if (maintenanceInterval > 0) {
|
|
232
|
+
maintenanceLoop = startMaintenanceLoop({
|
|
233
|
+
intervalMs: maintenanceInterval,
|
|
234
|
+
queueDir: QUEUE_DIR,
|
|
235
|
+
dbPath: DB_PATH,
|
|
236
|
+
statePath: MAINTENANCE_STATE_PATH,
|
|
237
|
+
runner: `api:${process.pid}`,
|
|
238
|
+
});
|
|
239
|
+
console.log(`🧹 Maintenance pass every ${Math.round(maintenanceInterval / 60_000)} min (in-process)`);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
console.log('🧹 Maintenance loop disabled — an external scheduler is expected to run it.');
|
|
243
|
+
}
|
|
244
|
+
// In-flight work finishes before the process goes: a pass killed mid-write
|
|
245
|
+
// leaves a job in `.processing` that only the stale-lock timeout recovers.
|
|
246
|
+
const shutdown = (signal) => {
|
|
247
|
+
console.log(`\n${signal} — stopping maintenance loop and closing the store.`);
|
|
248
|
+
maintenanceLoop?.stop();
|
|
249
|
+
try {
|
|
250
|
+
store.close?.();
|
|
251
|
+
}
|
|
252
|
+
catch { /* already closed */ }
|
|
253
|
+
process.exit(0);
|
|
254
|
+
};
|
|
255
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
256
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
210
257
|
}
|
package/dist/cli/index.js
CHANGED
|
@@ -792,6 +792,58 @@ for (const verb of ['approve', 'reject']) {
|
|
|
792
792
|
}
|
|
793
793
|
});
|
|
794
794
|
}
|
|
795
|
+
// === MAINTENANCE ===
|
|
796
|
+
const maintenance = program
|
|
797
|
+
.command('maintenance')
|
|
798
|
+
.description('Health of the consolidation loop, and a way to force a pass');
|
|
799
|
+
maintenance
|
|
800
|
+
.command('status', { isDefault: true })
|
|
801
|
+
.description('Is consolidation still running, and when did it last succeed?')
|
|
802
|
+
.option('--json', 'Machine-readable output')
|
|
803
|
+
.option('--stale-after <minutes>', 'Staleness budget before the loop is called overdue', '60')
|
|
804
|
+
.action(async (options) => {
|
|
805
|
+
const { readMaintenanceState, assessMaintenance, defaultStatePath } = await import('../agent/maintenance-state.js');
|
|
806
|
+
const staleAfterMs = Math.max(1, Number(options.staleAfter)) * 60_000;
|
|
807
|
+
const health = assessMaintenance(await readMaintenanceState(defaultStatePath(QUEUE_DIR)), { staleAfterMs });
|
|
808
|
+
if (options.json) {
|
|
809
|
+
console.log(JSON.stringify(health, null, 2));
|
|
810
|
+
}
|
|
811
|
+
else {
|
|
812
|
+
console.log(`\n${health.stale ? '✗' : '✓'} ${health.summary}`);
|
|
813
|
+
if (health.lastRunAt)
|
|
814
|
+
console.log(` last attempt ${health.lastRunAt}`);
|
|
815
|
+
if (health.lastSuccessAt)
|
|
816
|
+
console.log(` last success ${health.lastSuccessAt}`);
|
|
817
|
+
if (health.lastError)
|
|
818
|
+
console.log(` last error ${health.lastError}`);
|
|
819
|
+
if (health.lastResult) {
|
|
820
|
+
const r = health.lastResult;
|
|
821
|
+
console.log(` last counts ${r.processed}/${r.discovered} jobs, ${r.memoriesStored} memories, ${r.failed} failed, ${r.deadLettered} dead-lettered`);
|
|
822
|
+
}
|
|
823
|
+
console.log();
|
|
824
|
+
if (health.stale) {
|
|
825
|
+
console.log('The loop lives in the API process — check that it is running, then `humemory maintenance run`.\n');
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
// Non-zero on staleness so a checker can act on it without parsing text.
|
|
829
|
+
if (health.stale)
|
|
830
|
+
process.exitCode = 1;
|
|
831
|
+
});
|
|
832
|
+
maintenance
|
|
833
|
+
.command('run')
|
|
834
|
+
.description('Force one consolidation pass here and now, in this process')
|
|
835
|
+
.option('--skip-codex', 'Do not import codex rollouts first')
|
|
836
|
+
.action(async (options) => {
|
|
837
|
+
const { runMaintenancePass, resolveMaintenanceClient } = await import('../agent/maintenance-runner.js');
|
|
838
|
+
const client = await resolveMaintenanceClient();
|
|
839
|
+
const { worker } = await runMaintenancePass({
|
|
840
|
+
client,
|
|
841
|
+
codexSinceDays: options.skipCodex ? false : undefined,
|
|
842
|
+
runner: 'cli',
|
|
843
|
+
});
|
|
844
|
+
console.log(`✓ ${worker.processed}/${worker.discovered} jobs, ${worker.memoriesStored} memories, ` +
|
|
845
|
+
`${worker.failed} failed, ${worker.deadLettered} dead-lettered${worker.busy ? ' (another worker held the lock)' : ''}`);
|
|
846
|
+
});
|
|
795
847
|
// === LOCAL AGENT SOURCES ===
|
|
796
848
|
const sources = program
|
|
797
849
|
.command('sources')
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "humemory",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"description": "Memory for AI agents that forgets like a human — decaying traces, inverse search, and prospective loops that resurface on a cue",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -88,6 +88,8 @@
|
|
|
88
88
|
"cli": "bun run src/cli/index.ts",
|
|
89
89
|
"consolidate": "bun run scripts/consolidate.js",
|
|
90
90
|
"maintenance": "bun run scripts/maintenance-worker.ts",
|
|
91
|
+
"maintenance:status": "bun run src/cli/index.ts maintenance status",
|
|
92
|
+
"win:install": "pwsh -File scripts/windows/install.ps1",
|
|
91
93
|
"dream": "bun run src/cli/index.ts dream",
|
|
92
94
|
"mcp": "bun run src/mcp/server.ts",
|
|
93
95
|
"build:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\" && bun build web/index.html --outdir public/app --production --splitting",
|
|
@@ -1,37 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
/**
|
|
2
|
+
/**
|
|
3
|
+
* One non-blocking maintenance pass over sessions queued by local agent hooks.
|
|
4
|
+
*
|
|
5
|
+
* The pass itself lives in src/agent/maintenance-runner.ts, shared with the API
|
|
6
|
+
* process, which runs it on a timer. This script stays for manual runs
|
|
7
|
+
* (`pnpm maintenance`) and for a machine that does not keep the API resident.
|
|
8
|
+
*/
|
|
3
9
|
|
|
4
|
-
import
|
|
5
|
-
import { dirname, join } from 'path';
|
|
6
|
-
import { fileURLToPath } from 'url';
|
|
7
|
-
import type { LLMClient } from '../src/core/llm-generator.js';
|
|
8
|
-
import { createCodexClient } from '../src/core/llm-cli-client.js';
|
|
9
|
-
import { processMaintenanceQueue } from '../src/agent/maintenance-queue.js';
|
|
10
|
+
import { runMaintenancePass, resolveMaintenanceClient, defaultLlmTimeoutMs } from '../src/agent/maintenance-runner.js';
|
|
10
11
|
|
|
11
|
-
const
|
|
12
|
-
const
|
|
13
|
-
const dbPath = process.env.HUMEMORY_DB ?? join(__dirname, '../data/humemory.db');
|
|
14
|
-
const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? 'none';
|
|
12
|
+
const llmTimeoutMs = defaultLlmTimeoutMs();
|
|
13
|
+
const client = await resolveMaintenanceClient(llmTimeoutMs);
|
|
15
14
|
|
|
16
|
-
|
|
15
|
+
// --skip-codex for a machine where the rollouts are imported some other way.
|
|
16
|
+
const codexSinceDays = process.argv.includes('--skip-codex')
|
|
17
|
+
? false as const
|
|
18
|
+
: Number(process.env.HUMEMORY_MAINTENANCE_CODEX_DAYS ?? 1);
|
|
17
19
|
|
|
18
|
-
|
|
19
|
-
let client: LLMClient | undefined;
|
|
20
|
-
if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
|
|
21
|
-
client = new Anthropic() as unknown as LLMClient;
|
|
22
|
-
} else if (provider === 'codex') {
|
|
23
|
-
// No API key needed: the logged-in `codex` CLI answers instead. Slower than an
|
|
24
|
-
// SDK call (agent start-up), so it gets its own, larger budget.
|
|
25
|
-
client = createCodexClient({ timeoutMs: llmTimeoutMs });
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const result = await processMaintenanceQueue({
|
|
29
|
-
queueDir,
|
|
30
|
-
dbPath,
|
|
31
|
-
client,
|
|
32
|
-
llmTimeoutMs,
|
|
33
|
-
maxJobs: Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
|
|
34
|
-
});
|
|
20
|
+
const { worker: result } = await runMaintenancePass({ client, llmTimeoutMs, codexSinceDays });
|
|
35
21
|
|
|
36
22
|
if (result.busy) {
|
|
37
23
|
if (process.env.HUMEMORY_VERBOSE === '1') console.error('[humemory] maintenance: another worker is active');
|