humemory 0.2.11 → 0.2.13
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/AGENTS.md +43 -25
- package/CHANGELOG.md +16 -0
- package/README.md +31 -16
- package/dist/agent/claude-hook.d.ts +7 -0
- package/dist/agent/claude-hook.js +23 -3
- package/dist/agent/jev-advisor.d.ts +37 -0
- package/dist/agent/jev-advisor.js +139 -0
- package/dist/agent/maintenance-queue.d.ts +3 -0
- package/dist/agent/maintenance-queue.js +2 -0
- package/dist/agent/maintenance-runner.d.ts +13 -3
- package/dist/agent/maintenance-runner.js +60 -10
- package/dist/agent/memory-advisor.d.ts +86 -0
- package/dist/agent/memory-advisor.js +162 -0
- package/dist/cli/index.js +3 -1
- package/dist/core/kimi-llm-client.d.ts +30 -0
- package/dist/core/kimi-llm-client.js +228 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/docs/KIMI_EXPERIMENT_RESOLUTION.md +9 -0
- package/docs/TESTING.md +22 -13
- package/docs/architecture/architecture.html +230 -0
- package/package.json +2 -1
- package/scripts/maintenance-worker.ts +8 -2
- package/src/agent/claude-hook.ts +34 -3
- package/src/agent/jev-advisor.ts +191 -0
- package/src/agent/maintenance-queue.ts +5 -0
- package/src/agent/maintenance-runner.ts +66 -9
- package/src/agent/memory-advisor.ts +237 -0
- package/src/cli/index.ts +3 -1
- package/src/core/kimi-llm-client.ts +180 -0
- package/src/index.ts +7 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SALIENCE_BANDS,
|
|
3
|
+
type MemoryAdvice,
|
|
4
|
+
type MemoryAdvisor,
|
|
5
|
+
type SalienceBand,
|
|
6
|
+
type SanitizedMemoryCandidate,
|
|
7
|
+
} from './memory-advisor.js';
|
|
8
|
+
import type { MemoryType } from '../core/types.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* TypeSafe System One adapter for automatic-memory qualification.
|
|
12
|
+
* Acquisition rules and privacy checks stay in `memory-advisor.ts`; this file
|
|
13
|
+
* only translates a sanitized candidate to and from the provider schema.
|
|
14
|
+
*/
|
|
15
|
+
export type JevMode = 'off' | 'shadow' | 'advisory';
|
|
16
|
+
|
|
17
|
+
type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
18
|
+
|
|
19
|
+
export interface JevAdvisorOptions {
|
|
20
|
+
apiKey: string;
|
|
21
|
+
endpoint?: string;
|
|
22
|
+
model?: string;
|
|
23
|
+
/** Per-request deadline. Native fetch observes the AbortSignal below. */
|
|
24
|
+
timeoutMs?: number;
|
|
25
|
+
/** Test seam; production uses the runtime's native fetch. */
|
|
26
|
+
fetch?: FetchLike;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface JevAnswerMap {
|
|
30
|
+
should_store?: { type?: unknown; noul?: unknown };
|
|
31
|
+
memory_type?: { type?: unknown; choice?: unknown; confidence?: unknown };
|
|
32
|
+
salience_band?: { type?: unknown; score?: unknown; confidence?: unknown };
|
|
33
|
+
contains_sensitive_material?: { type?: unknown; noul?: unknown };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function finiteProbability(value: unknown, name: string): number {
|
|
37
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
|
|
38
|
+
throw new Error(`Malformed Jev ${name}`);
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function memoryType(value: unknown): MemoryType {
|
|
44
|
+
if (value === 'episodic' || value === 'semantic' || value === 'procedural') return value;
|
|
45
|
+
throw new Error('Malformed Jev memory_type');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function salienceBand(value: unknown): SalienceBand {
|
|
49
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > SALIENCE_BANDS.length - 1) {
|
|
50
|
+
throw new Error('Malformed Jev salience_band');
|
|
51
|
+
}
|
|
52
|
+
return SALIENCE_BANDS[Math.round(value)];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** HTTP implementation of the provider-neutral `MemoryAdvisor` seam. */
|
|
56
|
+
export class JevMemoryAdvisor implements MemoryAdvisor {
|
|
57
|
+
private readonly apiKey: string;
|
|
58
|
+
private readonly endpoint: string;
|
|
59
|
+
private readonly model: string;
|
|
60
|
+
private readonly timeoutMs: number;
|
|
61
|
+
private readonly fetchImpl: FetchLike;
|
|
62
|
+
|
|
63
|
+
constructor(options: JevAdvisorOptions) {
|
|
64
|
+
if (!options.apiKey.trim()) throw new Error('TYPESAFE_API_KEY is required for Jev shadow mode');
|
|
65
|
+
this.apiKey = options.apiKey.trim();
|
|
66
|
+
this.endpoint = options.endpoint ?? 'https://api.typesafe.ai/v1/systemone';
|
|
67
|
+
this.model = options.model ?? 'jev-latest';
|
|
68
|
+
this.timeoutMs = options.timeoutMs ?? 3_000;
|
|
69
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async advise(candidate: SanitizedMemoryCandidate): Promise<MemoryAdvice> {
|
|
73
|
+
const controller = new AbortController();
|
|
74
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
75
|
+
try {
|
|
76
|
+
const response = await this.fetchImpl(this.endpoint, {
|
|
77
|
+
method: 'POST',
|
|
78
|
+
headers: {
|
|
79
|
+
authorization: `Bearer ${this.apiKey}`,
|
|
80
|
+
'content-type': 'application/json',
|
|
81
|
+
},
|
|
82
|
+
signal: controller.signal,
|
|
83
|
+
body: JSON.stringify({
|
|
84
|
+
state: {
|
|
85
|
+
candidate: candidate.content,
|
|
86
|
+
current_memory_type: candidate.currentMemoryType,
|
|
87
|
+
},
|
|
88
|
+
model: this.model,
|
|
89
|
+
questions: {
|
|
90
|
+
should_store: {
|
|
91
|
+
type: 'noul',
|
|
92
|
+
instructions: 'Should this candidate become durable memory for a future AI agent working on the same project?',
|
|
93
|
+
criteria: {
|
|
94
|
+
true: 'Durable decision, solved problem, reusable procedure, or stable project fact',
|
|
95
|
+
false: 'Transient output, conversational filler, unverified plan, repetition, or one-off observation',
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
memory_type: {
|
|
99
|
+
type: 'choice',
|
|
100
|
+
instructions: 'Which cognitive memory type best describes this candidate?',
|
|
101
|
+
criteria: {
|
|
102
|
+
episodic: 'A particular event or session-bound occurrence',
|
|
103
|
+
semantic: 'A stable fact, rule, or concept',
|
|
104
|
+
procedural: 'A reusable method, skill, or sequence of actions',
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
salience_band: {
|
|
108
|
+
type: 'score',
|
|
109
|
+
instructions: 'How important is this candidate to future work on the same project?',
|
|
110
|
+
criteria: [
|
|
111
|
+
'Discard: no durable value',
|
|
112
|
+
'Low: occasionally useful context',
|
|
113
|
+
'Normal: useful project memory',
|
|
114
|
+
'High: important decision or reliable procedure',
|
|
115
|
+
'Exceptional: critical safety rule or foundational invariant',
|
|
116
|
+
],
|
|
117
|
+
},
|
|
118
|
+
contains_sensitive_material: {
|
|
119
|
+
type: 'noul',
|
|
120
|
+
instructions: 'Does the already-redacted candidate still appear to contain private credentials, personal identity, or confidential machine details?',
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
}),
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
if (!response.ok) throw new Error(`Jev request failed with status ${response.status}`);
|
|
127
|
+
const payload = await response.json() as { answers?: JevAnswerMap };
|
|
128
|
+
const answers = payload.answers;
|
|
129
|
+
// Do not coerce partial provider output. Throwing here becomes a
|
|
130
|
+
// content-free `provider_failure` record at the shadow boundary.
|
|
131
|
+
if (!answers || answers.should_store?.type !== 'noul' || answers.memory_type?.type !== 'choice'
|
|
132
|
+
|| answers.salience_band?.type !== 'score' || answers.contains_sensitive_material?.type !== 'noul') {
|
|
133
|
+
throw new Error('Malformed Jev response');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
shouldStore: finiteProbability(answers.should_store.noul, 'should_store'),
|
|
138
|
+
memoryType: memoryType(answers.memory_type.choice),
|
|
139
|
+
memoryTypeConfidence: finiteProbability(answers.memory_type.confidence, 'memory_type confidence'),
|
|
140
|
+
salienceBand: salienceBand(answers.salience_band.score),
|
|
141
|
+
provider: 'jev',
|
|
142
|
+
containsSensitiveMaterial: finiteProbability(
|
|
143
|
+
answers.contains_sensitive_material.noul,
|
|
144
|
+
'contains_sensitive_material',
|
|
145
|
+
),
|
|
146
|
+
};
|
|
147
|
+
} finally {
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Requested mode and the narrower mode this release is allowed to execute. */
|
|
154
|
+
export interface ConfiguredJevAdvisor {
|
|
155
|
+
requestedMode: JevMode;
|
|
156
|
+
effectiveMode: 'off' | 'shadow';
|
|
157
|
+
advisor?: MemoryAdvisor;
|
|
158
|
+
unavailableReason?: 'missing_api_key';
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function requestedMode(env: NodeJS.ProcessEnv): JevMode {
|
|
162
|
+
const value = env.HUMEMORY_JEV_MODE?.trim().toLowerCase();
|
|
163
|
+
return value === 'shadow' || value === 'advisory' ? value : 'off';
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** API-key presence alone is inert. Advisory is deliberately capped to shadow. */
|
|
167
|
+
export function resolveConfiguredJevAdvisor(
|
|
168
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
169
|
+
fetchImpl?: FetchLike,
|
|
170
|
+
): ConfiguredJevAdvisor {
|
|
171
|
+
const requested = requestedMode(env);
|
|
172
|
+
if (requested === 'off') return { requestedMode: requested, effectiveMode: 'off' };
|
|
173
|
+
const apiKey = env.TYPESAFE_API_KEY?.trim();
|
|
174
|
+
if (!apiKey) {
|
|
175
|
+
return {
|
|
176
|
+
requestedMode: requested,
|
|
177
|
+
effectiveMode: 'shadow',
|
|
178
|
+
unavailableReason: 'missing_api_key',
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
requestedMode: requested,
|
|
183
|
+
effectiveMode: 'shadow',
|
|
184
|
+
advisor: new JevMemoryAdvisor({
|
|
185
|
+
apiKey,
|
|
186
|
+
model: env.HUMEMORY_JEV_MODEL?.trim() || 'jev-latest',
|
|
187
|
+
timeoutMs: Number(env.HUMEMORY_JEV_TIMEOUT_MS ?? 3_000),
|
|
188
|
+
fetch: fetchImpl,
|
|
189
|
+
}),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -5,6 +5,7 @@ import type { LLMClient } from '../core/llm-generator.js';
|
|
|
5
5
|
import { processSession } from './claude-hook.js';
|
|
6
6
|
import { parseAgentSession } from './session-parser.js';
|
|
7
7
|
import { AdvisoryLock } from '../store/sqlite.js';
|
|
8
|
+
import type { MemoryAdvisor, ShadowDecisionReporter } from './memory-advisor.js';
|
|
8
9
|
|
|
9
10
|
export interface MaintenanceJob {
|
|
10
11
|
version: 1;
|
|
@@ -43,6 +44,8 @@ export interface WorkerOptions {
|
|
|
43
44
|
queueDir: string;
|
|
44
45
|
dbPath: string;
|
|
45
46
|
client?: LLMClient;
|
|
47
|
+
memoryAdvisor?: MemoryAdvisor;
|
|
48
|
+
advisorReporter?: ShadowDecisionReporter;
|
|
46
49
|
llmTimeoutMs?: number;
|
|
47
50
|
maxJobs?: number;
|
|
48
51
|
maxAttempts?: number;
|
|
@@ -318,6 +321,8 @@ export async function processMaintenanceQueue(options: WorkerOptions): Promise<W
|
|
|
318
321
|
directory: job.directory,
|
|
319
322
|
maxLearnings: job.maxLearnings,
|
|
320
323
|
client: options.client,
|
|
324
|
+
memoryAdvisor: options.memoryAdvisor,
|
|
325
|
+
advisorReporter: options.advisorReporter,
|
|
321
326
|
llmTimeoutMs: options.llmTimeoutMs,
|
|
322
327
|
source: 'hook',
|
|
323
328
|
agent: job.agent,
|
|
@@ -16,11 +16,19 @@
|
|
|
16
16
|
|
|
17
17
|
import { dirname, join } from 'path';
|
|
18
18
|
import { fileURLToPath } from 'url';
|
|
19
|
+
import { readFileSync } from 'fs';
|
|
19
20
|
import type { LLMClient } from '../core/llm-generator.js';
|
|
20
21
|
import type { Clock } from '../core/clock.js';
|
|
21
22
|
import { systemClock } from '../core/clock.js';
|
|
22
23
|
import { databasePath, queueDirectory } from '../core/paths.js';
|
|
23
24
|
import { createCodexClient } from '../core/llm-cli-client.js';
|
|
25
|
+
import { createKimiClient } from '../core/kimi-llm-client.js';
|
|
26
|
+
import { resolveConfiguredJevAdvisor } from './jev-advisor.js';
|
|
27
|
+
import {
|
|
28
|
+
jsonlShadowReporter,
|
|
29
|
+
type MemoryAdvisor,
|
|
30
|
+
type ShadowDecisionReporter,
|
|
31
|
+
} from './memory-advisor.js';
|
|
24
32
|
import { processMaintenanceQueue, type WorkerResult } from './maintenance-queue.js';
|
|
25
33
|
import { importCodexRollouts, defaultCodexSessionsDir, type CodexImportResult } from './codex-import.js';
|
|
26
34
|
import { importKimiSessions, defaultKimiHome, type KimiImportResult } from './kimi-import.js';
|
|
@@ -53,6 +61,9 @@ export interface MaintenancePassOptions {
|
|
|
53
61
|
opencodeRun?: OpenCodeCommandRunner;
|
|
54
62
|
opencodeCommand?: string;
|
|
55
63
|
client?: LLMClient;
|
|
64
|
+
/** `false` is an explicit test/operator override even when env selects shadow mode. */
|
|
65
|
+
memoryAdvisor?: MemoryAdvisor | false;
|
|
66
|
+
advisorReporter?: ShadowDecisionReporter;
|
|
56
67
|
llmTimeoutMs?: number;
|
|
57
68
|
maxJobs?: number;
|
|
58
69
|
clock?: Clock;
|
|
@@ -78,8 +89,13 @@ export function defaultDbPath(): string {
|
|
|
78
89
|
return databasePath();
|
|
79
90
|
}
|
|
80
91
|
|
|
81
|
-
|
|
82
|
-
return
|
|
92
|
+
function localLlmConfiguration(dbPath = defaultDbPath()): any {
|
|
93
|
+
try { return JSON.parse(readFileSync(join(dirname(dbPath), 'maintenance-llm.json'), 'utf8')); }
|
|
94
|
+
catch (e: any) { if (e.code === 'ENOENT') return {}; throw e; }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function defaultLlmTimeoutMs(dbPath = defaultDbPath()): number {
|
|
98
|
+
return Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? localLlmConfiguration(dbPath).timeoutMs ?? 8_000);
|
|
83
99
|
}
|
|
84
100
|
|
|
85
101
|
export function configuredIntervalMs(): number {
|
|
@@ -90,12 +106,17 @@ export function configuredIntervalMs(): number {
|
|
|
90
106
|
/**
|
|
91
107
|
* The LLM the pass consolidates with. 'none' (the default) keeps consolidation
|
|
92
108
|
* deterministic and network-free; there is no API key on the production machine
|
|
93
|
-
* and none wanted, so
|
|
109
|
+
* and none wanted, so CLI providers use the logged-in subscription instead.
|
|
110
|
+
* Local provider settings require enabled=true; an environment override remains explicit.
|
|
94
111
|
*/
|
|
95
112
|
export async function resolveMaintenanceClient(
|
|
96
|
-
timeoutMs =
|
|
113
|
+
timeoutMs: number | undefined = undefined,
|
|
114
|
+
dbPath = defaultDbPath(),
|
|
115
|
+
queueDir = defaultQueueDir(),
|
|
97
116
|
): Promise<LLMClient | undefined> {
|
|
98
|
-
const
|
|
117
|
+
const config = localLlmConfiguration(dbPath);
|
|
118
|
+
const timeout = timeoutMs ?? defaultLlmTimeoutMs(dbPath);
|
|
119
|
+
const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? (config.enabled === true ? config.provider : 'none') ?? 'none';
|
|
99
120
|
|
|
100
121
|
if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
|
|
101
122
|
const { default: Anthropic } = await import('@anthropic-ai/sdk');
|
|
@@ -104,11 +125,28 @@ export async function resolveMaintenanceClient(
|
|
|
104
125
|
if (provider === 'codex') {
|
|
105
126
|
// No API key needed: the logged-in `codex` CLI answers instead. Slower than
|
|
106
127
|
// an SDK call (agent start-up), so it gets its own, larger budget.
|
|
107
|
-
return createCodexClient({ timeoutMs });
|
|
128
|
+
return createCodexClient({ timeoutMs: timeout });
|
|
129
|
+
}
|
|
130
|
+
if (provider === 'kimi') {
|
|
131
|
+
return createKimiClient({ model: process.env.HUMEMORY_LLM_MODEL ?? config.model ?? 'kimi-code/k3-256k',
|
|
132
|
+
timeoutMs: Math.min(timeout, 60_000), statePath: join(dirname(dbPath), 'kimi-llm-budget.json'), queueDir,
|
|
133
|
+
maxCallsPerDay: config.maxCallsPerDay ?? 2, quotaStopPercent: config.quotaStopPercent ?? 24 });
|
|
108
134
|
}
|
|
109
135
|
return undefined;
|
|
110
136
|
}
|
|
111
137
|
|
|
138
|
+
/** Resolve Jev only at executable entry points, never inside the hermetic pass. */
|
|
139
|
+
export function resolveMaintenanceAdvisor(
|
|
140
|
+
dbPath = defaultDbPath(),
|
|
141
|
+
): { memoryAdvisor?: MemoryAdvisor; advisorReporter?: ShadowDecisionReporter } {
|
|
142
|
+
const configured = resolveConfiguredJevAdvisor();
|
|
143
|
+
if (!configured.advisor) return {};
|
|
144
|
+
return {
|
|
145
|
+
memoryAdvisor: configured.advisor,
|
|
146
|
+
advisorReporter: jsonlShadowReporter(join(dirname(dbPath), 'jev-shadow.jsonl')),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
112
150
|
/**
|
|
113
151
|
* Import, then drain, then record. Every producer is isolated: a missing or
|
|
114
152
|
* unreadable runtime must never stall the queue or another producer.
|
|
@@ -123,11 +161,15 @@ export async function runMaintenancePass(
|
|
|
123
161
|
const queueDir = options.queueDir ?? defaultQueueDir();
|
|
124
162
|
const dbPath = options.dbPath ?? defaultDbPath();
|
|
125
163
|
const statePath = options.statePath ?? defaultStatePath(queueDir);
|
|
126
|
-
const llmTimeoutMs = options.llmTimeoutMs ?? defaultLlmTimeoutMs();
|
|
164
|
+
const llmTimeoutMs = options.llmTimeoutMs ?? defaultLlmTimeoutMs(dbPath);
|
|
127
165
|
const codexSinceDays = options.codexSinceDays ?? 1;
|
|
128
166
|
const kimiSinceDays = options.kimiSinceDays ?? 1;
|
|
129
167
|
const opencodeSinceDays = options.opencodeSinceDays ?? 1;
|
|
130
168
|
const startedAt = clock.now();
|
|
169
|
+
// No environment lookup here. Tests and library callers get a hermetic pass
|
|
170
|
+
// unless an executable entry point injects an advisor.
|
|
171
|
+
const memoryAdvisor = options.memoryAdvisor === false ? undefined : options.memoryAdvisor;
|
|
172
|
+
const advisorReporter = options.advisorReporter;
|
|
131
173
|
|
|
132
174
|
let codex: CodexImportResult | undefined;
|
|
133
175
|
let codexError: string | undefined;
|
|
@@ -180,6 +222,8 @@ export async function runMaintenancePass(
|
|
|
180
222
|
queueDir,
|
|
181
223
|
dbPath,
|
|
182
224
|
client: options.client,
|
|
225
|
+
memoryAdvisor,
|
|
226
|
+
advisorReporter,
|
|
183
227
|
llmTimeoutMs,
|
|
184
228
|
maxJobs: options.maxJobs ?? Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
|
|
185
229
|
now: () => clock.now(),
|
|
@@ -288,8 +332,21 @@ export function startMaintenanceLoop(options: MaintenanceLoopOptions = {}): Main
|
|
|
288
332
|
if (running || stopped) return;
|
|
289
333
|
running = true;
|
|
290
334
|
try {
|
|
291
|
-
const client = options.client ?? await resolveMaintenanceClient(options.llmTimeoutMs
|
|
292
|
-
|
|
335
|
+
const client = options.client ?? await resolveMaintenanceClient(options.llmTimeoutMs,
|
|
336
|
+
options.dbPath ?? defaultDbPath(), options.queueDir ?? defaultQueueDir());
|
|
337
|
+
// The resident API loop is an executable entry point, so it may resolve
|
|
338
|
+
// the opt-in provider. `runMaintenancePass` itself remains environment-free.
|
|
339
|
+
const advisor = options.memoryAdvisor === false
|
|
340
|
+
? {}
|
|
341
|
+
: options.memoryAdvisor
|
|
342
|
+
? { memoryAdvisor: options.memoryAdvisor, advisorReporter: options.advisorReporter }
|
|
343
|
+
: resolveMaintenanceAdvisor(options.dbPath ?? defaultDbPath());
|
|
344
|
+
const { worker } = await runMaintenancePass({
|
|
345
|
+
...options,
|
|
346
|
+
...advisor,
|
|
347
|
+
client,
|
|
348
|
+
runner: options.runner ?? 'api-loop',
|
|
349
|
+
});
|
|
293
350
|
if (process.env.HUMEMORY_VERBOSE === '1' || worker.failed > 0) {
|
|
294
351
|
console.error(
|
|
295
352
|
`[humemory] maintenance: ${worker.processed}/${worker.discovered} jobs, ` +
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
import { appendFile, mkdir } from 'fs/promises';
|
|
3
|
+
import { dirname } from 'path';
|
|
4
|
+
import type { MemoryType, TraceSource } from '../core/types.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Acquisition-side advice contract.
|
|
8
|
+
*
|
|
9
|
+
* This module owns the local privacy gate and shadow reporting. It does not
|
|
10
|
+
* own storage policy: while shadow mode is active, callers keep the baseline
|
|
11
|
+
* learning even when the provider disagrees or fails.
|
|
12
|
+
*/
|
|
13
|
+
export const SALIENCE_BANDS = ['discard', 'low', 'normal', 'high', 'exceptional'] as const;
|
|
14
|
+
export type SalienceBand = typeof SALIENCE_BANDS[number];
|
|
15
|
+
|
|
16
|
+
export interface MemoryAdvice {
|
|
17
|
+
shouldStore: number;
|
|
18
|
+
memoryType: MemoryType;
|
|
19
|
+
memoryTypeConfidence: number | null;
|
|
20
|
+
salienceBand: SalienceBand;
|
|
21
|
+
provider: 'jev';
|
|
22
|
+
/** Experimental signal only. Privacy has already been decided locally. */
|
|
23
|
+
containsSensitiveMaterial?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SanitizedMemoryCandidate {
|
|
27
|
+
content: string;
|
|
28
|
+
currentMemoryType: MemoryType;
|
|
29
|
+
source: TraceSource;
|
|
30
|
+
truncated: boolean;
|
|
31
|
+
redactions: Array<'path' | 'identity' | 'command_output'>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Provider-neutral seam. Implementations only receive locally approved text. */
|
|
35
|
+
export interface MemoryAdvisor {
|
|
36
|
+
advise(candidate: SanitizedMemoryCandidate): Promise<MemoryAdvice>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface AutomaticMemoryCandidate {
|
|
40
|
+
content: string;
|
|
41
|
+
currentMemoryType: MemoryType;
|
|
42
|
+
source: TraceSource;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type CandidateRejectionReason = 'source_not_allowed' | 'sensitive_material' | 'empty_after_redaction';
|
|
46
|
+
|
|
47
|
+
export type CandidateSanitization =
|
|
48
|
+
| { accepted: true; hash: string; candidate: SanitizedMemoryCandidate }
|
|
49
|
+
| { accepted: false; hash: string; reason: CandidateRejectionReason };
|
|
50
|
+
|
|
51
|
+
export interface SanitizeCandidateOptions {
|
|
52
|
+
maxCharacters?: number;
|
|
53
|
+
allowedSources?: ReadonlySet<TraceSource>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const DEFAULT_ALLOWED_SOURCES: ReadonlySet<TraceSource> = new Set(['hook']);
|
|
57
|
+
|
|
58
|
+
const SENSITIVE_PATTERNS = [
|
|
59
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----/i,
|
|
60
|
+
/\b(?:authorization|proxy-authorization)\s*[:=]\s*(?:bearer|basic)\s+\S+/i,
|
|
61
|
+
/\b(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|password|passwd)\s*[:=]\s*["']?[^\s"']{8,}/i,
|
|
62
|
+
/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|AKIA[A-Z0-9]{16})\b/,
|
|
63
|
+
];
|
|
64
|
+
|
|
65
|
+
function candidateHash(content: string): string {
|
|
66
|
+
return createHash('sha256').update(content).digest('hex');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function redactCandidateContent(content: string): { content: string; redactions: SanitizedMemoryCandidate['redactions'] } {
|
|
70
|
+
const redactions = new Set<SanitizedMemoryCandidate['redactions'][number]>();
|
|
71
|
+
let sanitized = content.replace(/\r\n/g, '\n');
|
|
72
|
+
|
|
73
|
+
sanitized = sanitized.replace(/\b[A-Za-z]:\\(?:[^\s<>:"|?*]+\\)*[^\s<>:"|?*]*/g, () => {
|
|
74
|
+
redactions.add('path');
|
|
75
|
+
return '<path>';
|
|
76
|
+
});
|
|
77
|
+
sanitized = sanitized.replace(/(?<![:\w])\/(?:Users|home|private|tmp|var|etc|opt|srv|mnt|workspace)\/[^\s'"`]+/g, () => {
|
|
78
|
+
redactions.add('path');
|
|
79
|
+
return '<path>';
|
|
80
|
+
});
|
|
81
|
+
sanitized = sanitized.replace(/\b[\w.-]+@[\w.-]+\b/g, () => {
|
|
82
|
+
redactions.add('identity');
|
|
83
|
+
return '<identity>';
|
|
84
|
+
});
|
|
85
|
+
sanitized = sanitized.replace(/\b(?:host(?:name)?|computer(?:name)?|user(?:name)?)\s*[:=]\s*[^\s,;]+/gi, (match) => {
|
|
86
|
+
redactions.add('identity');
|
|
87
|
+
return `${match.split(/[:=]/, 1)[0]}=<identity>`;
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const lines = sanitized.split('\n');
|
|
91
|
+
let suppressOutput = false;
|
|
92
|
+
const kept: string[] = [];
|
|
93
|
+
for (const line of lines) {
|
|
94
|
+
if (/^\s*(?:stdout|stderr|command output|sortie)\s*:/i.test(line)) {
|
|
95
|
+
if (!suppressOutput) kept.push('<command-output>');
|
|
96
|
+
suppressOutput = true;
|
|
97
|
+
redactions.add('command_output');
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (suppressOutput && line.trim() !== '') continue;
|
|
101
|
+
if (suppressOutput) suppressOutput = false;
|
|
102
|
+
kept.push(line);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
content: kept.join('\n').replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim(),
|
|
107
|
+
redactions: [...redactions],
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Apply the local privacy gate before provider code can run.
|
|
113
|
+
*
|
|
114
|
+
* Known credentials reject the whole candidate. Paths and machine identities
|
|
115
|
+
* can be removed safely, so they are replaced before the character cap is
|
|
116
|
+
* applied. Human-authored memories are outside this automatic path.
|
|
117
|
+
*/
|
|
118
|
+
export function sanitizeMemoryCandidate(
|
|
119
|
+
input: AutomaticMemoryCandidate,
|
|
120
|
+
options: SanitizeCandidateOptions = {},
|
|
121
|
+
): CandidateSanitization {
|
|
122
|
+
const hash = candidateHash(input.content);
|
|
123
|
+
const allowedSources = options.allowedSources ?? DEFAULT_ALLOWED_SOURCES;
|
|
124
|
+
if (!allowedSources.has(input.source)) return { accepted: false, hash, reason: 'source_not_allowed' };
|
|
125
|
+
if (SENSITIVE_PATTERNS.some((pattern) => pattern.test(input.content))) {
|
|
126
|
+
return { accepted: false, hash, reason: 'sensitive_material' };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const redacted = redactCandidateContent(input.content);
|
|
130
|
+
if (!redacted.content) return { accepted: false, hash, reason: 'empty_after_redaction' };
|
|
131
|
+
const maxCharacters = options.maxCharacters ?? 1_200;
|
|
132
|
+
const truncated = redacted.content.length > maxCharacters;
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
accepted: true,
|
|
136
|
+
hash,
|
|
137
|
+
candidate: {
|
|
138
|
+
content: redacted.content.slice(0, maxCharacters),
|
|
139
|
+
currentMemoryType: input.currentMemoryType,
|
|
140
|
+
source: input.source,
|
|
141
|
+
truncated,
|
|
142
|
+
redactions: redacted.redactions,
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Keep provider output on a fixed local scale; Jev never writes a raw salience value. */
|
|
148
|
+
export function salienceForBand(band: SalienceBand): number {
|
|
149
|
+
return ({ discard: 0, low: 25, normal: 50, high: 75, exceptional: 100 })[band];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Safe-to-persist comparison metadata. Candidate text is absent by design. */
|
|
153
|
+
export interface ShadowDecisionRecord {
|
|
154
|
+
at: string;
|
|
155
|
+
mode: 'shadow';
|
|
156
|
+
candidateHash: string;
|
|
157
|
+
source: TraceSource;
|
|
158
|
+
baseline: { shouldStore: true; memoryType: MemoryType };
|
|
159
|
+
outcome: 'advised' | 'rejected' | 'failed';
|
|
160
|
+
latencyMs: number;
|
|
161
|
+
rejectionReason?: CandidateRejectionReason;
|
|
162
|
+
errorKind?: 'provider_failure';
|
|
163
|
+
advice?: MemoryAdvice & { mappedSaillance: number };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export type ShadowDecisionReporter = (record: ShadowDecisionRecord) => void | Promise<void>;
|
|
167
|
+
|
|
168
|
+
async function reportSafely(reporter: ShadowDecisionReporter | undefined, record: ShadowDecisionRecord): Promise<void> {
|
|
169
|
+
if (!reporter) return;
|
|
170
|
+
try {
|
|
171
|
+
await reporter(record);
|
|
172
|
+
} catch {
|
|
173
|
+
// A diagnostic sink must never decide whether a memory survives.
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Compare one automatic candidate with the advisor without changing the
|
|
179
|
+
* candidate or throwing into maintenance. The return value is for tests and
|
|
180
|
+
* reporting; it never controls whether the baseline learning is stored.
|
|
181
|
+
*/
|
|
182
|
+
export async function adviseInShadow(
|
|
183
|
+
input: AutomaticMemoryCandidate,
|
|
184
|
+
advisor: MemoryAdvisor,
|
|
185
|
+
reporter?: ShadowDecisionReporter,
|
|
186
|
+
now: () => Date = () => new Date(),
|
|
187
|
+
): Promise<ShadowDecisionRecord> {
|
|
188
|
+
const started = now().getTime();
|
|
189
|
+
const sanitized = sanitizeMemoryCandidate(input);
|
|
190
|
+
const base = {
|
|
191
|
+
at: now().toISOString(),
|
|
192
|
+
mode: 'shadow' as const,
|
|
193
|
+
candidateHash: sanitized.hash,
|
|
194
|
+
source: input.source,
|
|
195
|
+
baseline: { shouldStore: true as const, memoryType: input.currentMemoryType },
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
if (!sanitized.accepted) {
|
|
199
|
+
const record: ShadowDecisionRecord = {
|
|
200
|
+
...base,
|
|
201
|
+
outcome: 'rejected',
|
|
202
|
+
rejectionReason: sanitized.reason,
|
|
203
|
+
latencyMs: Math.max(0, now().getTime() - started),
|
|
204
|
+
};
|
|
205
|
+
await reportSafely(reporter, record);
|
|
206
|
+
return record;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
try {
|
|
210
|
+
const advice = await advisor.advise(sanitized.candidate);
|
|
211
|
+
const record: ShadowDecisionRecord = {
|
|
212
|
+
...base,
|
|
213
|
+
outcome: 'advised',
|
|
214
|
+
latencyMs: Math.max(0, now().getTime() - started),
|
|
215
|
+
advice: { ...advice, mappedSaillance: salienceForBand(advice.salienceBand) },
|
|
216
|
+
};
|
|
217
|
+
await reportSafely(reporter, record);
|
|
218
|
+
return record;
|
|
219
|
+
} catch {
|
|
220
|
+
const record: ShadowDecisionRecord = {
|
|
221
|
+
...base,
|
|
222
|
+
outcome: 'failed',
|
|
223
|
+
errorKind: 'provider_failure',
|
|
224
|
+
latencyMs: Math.max(0, now().getTime() - started),
|
|
225
|
+
};
|
|
226
|
+
await reportSafely(reporter, record);
|
|
227
|
+
return record;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Append metadata only; `ShadowDecisionRecord` has no field for candidate text. */
|
|
232
|
+
export function jsonlShadowReporter(path: string): ShadowDecisionReporter {
|
|
233
|
+
return async (record) => {
|
|
234
|
+
await mkdir(dirname(path), { recursive: true });
|
|
235
|
+
await appendFile(path, `${JSON.stringify(record)}\n`, 'utf8');
|
|
236
|
+
};
|
|
237
|
+
}
|
package/src/cli/index.ts
CHANGED
|
@@ -930,10 +930,12 @@ maintenance
|
|
|
930
930
|
.option('--skip-kimi', 'Do not import Kimi Code sessions first')
|
|
931
931
|
.option('--skip-opencode', 'Do not import OpenCode sessions first')
|
|
932
932
|
.action(async (options) => {
|
|
933
|
-
const { runMaintenancePass, resolveMaintenanceClient } = await import('../agent/maintenance-runner.js');
|
|
933
|
+
const { runMaintenancePass, resolveMaintenanceClient, resolveMaintenanceAdvisor } = await import('../agent/maintenance-runner.js');
|
|
934
934
|
const client = await resolveMaintenanceClient();
|
|
935
|
+
const advisor = resolveMaintenanceAdvisor();
|
|
935
936
|
const { worker } = await runMaintenancePass({
|
|
936
937
|
client,
|
|
938
|
+
...advisor,
|
|
937
939
|
codexSinceDays: options.skipImports || options.skipCodex ? false : 1,
|
|
938
940
|
kimiSinceDays: options.skipImports || options.skipKimi ? false : 1,
|
|
939
941
|
opencodeSinceDays: options.skipImports || options.skipOpencode ? false : 1,
|