humemory 0.2.11 → 0.2.12

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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.12] - 2026-09-20
4
+ **Features:**
5
+ - add Jev shadow qualification
6
+ - guard Kimi subscription consolidation
7
+
8
+ **Documentation:**
9
+ - clarify Jev shadow invariants
10
+
11
+
12
+
3
13
  ## [0.2.11] - 2026-09-08
4
14
  **Features:**
5
15
  - measure what the index rebuild actually costs
@@ -1,5 +1,6 @@
1
1
  import type { LLMClient } from '../core/llm-generator.js';
2
2
  import type { TraceSource } from '../core/types.js';
3
+ import { type MemoryAdvisor, type ShadowDecisionReporter } from './memory-advisor.js';
3
4
  export interface HookOptions {
4
5
  dbPath: string;
5
6
  directory?: string;
@@ -8,6 +9,10 @@ export interface HookOptions {
8
9
  llmTimeoutMs?: number;
9
10
  source?: TraceSource;
10
11
  agent?: string;
12
+ /** Optional automatic-candidate advisor. It is observational in this release. */
13
+ memoryAdvisor?: MemoryAdvisor;
14
+ /** Receives content-free comparisons; reporter failures never block storage. */
15
+ advisorReporter?: ShadowDecisionReporter;
11
16
  /**
12
17
  * Number of leading transcript messages already encoded for this session.
13
18
  * `Stop` fires once per turn and resends the whole transcript, so without a
@@ -22,6 +27,8 @@ export interface HookResult {
22
27
  memoriesStored: number;
23
28
  learnings: string[];
24
29
  extractionMode: 'llm' | 'deterministic';
30
+ /** Candidates inspected in shadow mode, including local privacy rejections. */
31
+ advisorComparisons: number;
25
32
  /** Total messages in the transcript — the checkpoint to persist after success. */
26
33
  messagesSeen: number;
27
34
  }
@@ -1,6 +1,7 @@
1
1
  import { SQLiteStore } from '../store/sqlite.js';
2
2
  import { lastMessageTime, parseAgentSession } from './session-parser.js';
3
3
  import { extractLearnings, extractLearningsDeterministic } from './learning-extractor.js';
4
+ import { adviseInShadow, } from './memory-advisor.js';
4
5
  async function withTimeout(promise, timeoutMs) {
5
6
  let timer;
6
7
  try {
@@ -27,7 +28,7 @@ export async function processSession(rawTranscript, options) {
27
28
  if (pending.length === 0) {
28
29
  return {
29
30
  sessionId: session.sessionId, directory: session.directory,
30
- memoriesStored: 0, learnings: [], extractionMode: 'deterministic', messagesSeen,
31
+ memoriesStored: 0, learnings: [], extractionMode: 'deterministic', advisorComparisons: 0, messagesSeen,
31
32
  };
32
33
  }
33
34
  const scoped = {
@@ -47,7 +48,25 @@ export async function processSession(rawTranscript, options) {
47
48
  }
48
49
  }
49
50
  if (learnings.length === 0) {
50
- return { sessionId: session.sessionId, directory: session.directory, memoriesStored: 0, learnings: [], extractionMode, messagesSeen };
51
+ return {
52
+ sessionId: session.sessionId, directory: session.directory, memoriesStored: 0,
53
+ learnings: [], extractionMode, advisorComparisons: 0, messagesSeen,
54
+ };
55
+ }
56
+ const source = options.source ?? 'agent';
57
+ let advisorComparisons = 0;
58
+ if (options.memoryAdvisor) {
59
+ // Advice is recorded before storage, but its value is intentionally ignored.
60
+ // `adviseInShadow` contains provider and reporter failures, so every learning
61
+ // below follows the same storage path it used before Jev existed.
62
+ for (const learning of learnings) {
63
+ await adviseInShadow({
64
+ content: learning.content,
65
+ currentMemoryType: learning.memoryType,
66
+ source,
67
+ }, options.memoryAdvisor, options.advisorReporter);
68
+ advisorComparisons += 1;
69
+ }
51
70
  }
52
71
  // What is encoded belongs to the day the session ran, not the day it was
53
72
  // read: a rollout sweep runs long after the fact, and dating every trace on
@@ -66,7 +85,7 @@ export async function processSession(rawTranscript, options) {
66
85
  sessionId: session.sessionId,
67
86
  memoryType: learning.memoryType,
68
87
  level3Keywords: learning.level3Keywords,
69
- source: options.source ?? 'agent',
88
+ source,
70
89
  agent: options.agent ?? 'unknown',
71
90
  });
72
91
  stored.push(learning.content.slice(0, 80));
@@ -81,6 +100,7 @@ export async function processSession(rawTranscript, options) {
81
100
  memoriesStored: stored.length,
82
101
  learnings: stored,
83
102
  extractionMode,
103
+ advisorComparisons,
84
104
  messagesSeen,
85
105
  };
86
106
  }
@@ -0,0 +1,37 @@
1
+ import { type MemoryAdvice, type MemoryAdvisor, type SanitizedMemoryCandidate } from './memory-advisor.js';
2
+ /**
3
+ * TypeSafe System One adapter for automatic-memory qualification.
4
+ * Acquisition rules and privacy checks stay in `memory-advisor.ts`; this file
5
+ * only translates a sanitized candidate to and from the provider schema.
6
+ */
7
+ export type JevMode = 'off' | 'shadow' | 'advisory';
8
+ type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
9
+ export interface JevAdvisorOptions {
10
+ apiKey: string;
11
+ endpoint?: string;
12
+ model?: string;
13
+ /** Per-request deadline. Native fetch observes the AbortSignal below. */
14
+ timeoutMs?: number;
15
+ /** Test seam; production uses the runtime's native fetch. */
16
+ fetch?: FetchLike;
17
+ }
18
+ /** HTTP implementation of the provider-neutral `MemoryAdvisor` seam. */
19
+ export declare class JevMemoryAdvisor implements MemoryAdvisor {
20
+ private readonly apiKey;
21
+ private readonly endpoint;
22
+ private readonly model;
23
+ private readonly timeoutMs;
24
+ private readonly fetchImpl;
25
+ constructor(options: JevAdvisorOptions);
26
+ advise(candidate: SanitizedMemoryCandidate): Promise<MemoryAdvice>;
27
+ }
28
+ /** Requested mode and the narrower mode this release is allowed to execute. */
29
+ export interface ConfiguredJevAdvisor {
30
+ requestedMode: JevMode;
31
+ effectiveMode: 'off' | 'shadow';
32
+ advisor?: MemoryAdvisor;
33
+ unavailableReason?: 'missing_api_key';
34
+ }
35
+ /** API-key presence alone is inert. Advisory is deliberately capped to shadow. */
36
+ export declare function resolveConfiguredJevAdvisor(env?: NodeJS.ProcessEnv, fetchImpl?: FetchLike): ConfiguredJevAdvisor;
37
+ export {};
@@ -0,0 +1,139 @@
1
+ import { SALIENCE_BANDS, } from './memory-advisor.js';
2
+ function finiteProbability(value, name) {
3
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
4
+ throw new Error(`Malformed Jev ${name}`);
5
+ }
6
+ return value;
7
+ }
8
+ function memoryType(value) {
9
+ if (value === 'episodic' || value === 'semantic' || value === 'procedural')
10
+ return value;
11
+ throw new Error('Malformed Jev memory_type');
12
+ }
13
+ function salienceBand(value) {
14
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > SALIENCE_BANDS.length - 1) {
15
+ throw new Error('Malformed Jev salience_band');
16
+ }
17
+ return SALIENCE_BANDS[Math.round(value)];
18
+ }
19
+ /** HTTP implementation of the provider-neutral `MemoryAdvisor` seam. */
20
+ export class JevMemoryAdvisor {
21
+ apiKey;
22
+ endpoint;
23
+ model;
24
+ timeoutMs;
25
+ fetchImpl;
26
+ constructor(options) {
27
+ if (!options.apiKey.trim())
28
+ throw new Error('TYPESAFE_API_KEY is required for Jev shadow mode');
29
+ this.apiKey = options.apiKey.trim();
30
+ this.endpoint = options.endpoint ?? 'https://api.typesafe.ai/v1/systemone';
31
+ this.model = options.model ?? 'jev-latest';
32
+ this.timeoutMs = options.timeoutMs ?? 3_000;
33
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
34
+ }
35
+ async advise(candidate) {
36
+ const controller = new AbortController();
37
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
38
+ try {
39
+ const response = await this.fetchImpl(this.endpoint, {
40
+ method: 'POST',
41
+ headers: {
42
+ authorization: `Bearer ${this.apiKey}`,
43
+ 'content-type': 'application/json',
44
+ },
45
+ signal: controller.signal,
46
+ body: JSON.stringify({
47
+ state: {
48
+ candidate: candidate.content,
49
+ current_memory_type: candidate.currentMemoryType,
50
+ },
51
+ model: this.model,
52
+ questions: {
53
+ should_store: {
54
+ type: 'noul',
55
+ instructions: 'Should this candidate become durable memory for a future AI agent working on the same project?',
56
+ criteria: {
57
+ true: 'Durable decision, solved problem, reusable procedure, or stable project fact',
58
+ false: 'Transient output, conversational filler, unverified plan, repetition, or one-off observation',
59
+ },
60
+ },
61
+ memory_type: {
62
+ type: 'choice',
63
+ instructions: 'Which cognitive memory type best describes this candidate?',
64
+ criteria: {
65
+ episodic: 'A particular event or session-bound occurrence',
66
+ semantic: 'A stable fact, rule, or concept',
67
+ procedural: 'A reusable method, skill, or sequence of actions',
68
+ },
69
+ },
70
+ salience_band: {
71
+ type: 'score',
72
+ instructions: 'How important is this candidate to future work on the same project?',
73
+ criteria: [
74
+ 'Discard: no durable value',
75
+ 'Low: occasionally useful context',
76
+ 'Normal: useful project memory',
77
+ 'High: important decision or reliable procedure',
78
+ 'Exceptional: critical safety rule or foundational invariant',
79
+ ],
80
+ },
81
+ contains_sensitive_material: {
82
+ type: 'noul',
83
+ instructions: 'Does the already-redacted candidate still appear to contain private credentials, personal identity, or confidential machine details?',
84
+ },
85
+ },
86
+ }),
87
+ });
88
+ if (!response.ok)
89
+ throw new Error(`Jev request failed with status ${response.status}`);
90
+ const payload = await response.json();
91
+ const answers = payload.answers;
92
+ // Do not coerce partial provider output. Throwing here becomes a
93
+ // content-free `provider_failure` record at the shadow boundary.
94
+ if (!answers || answers.should_store?.type !== 'noul' || answers.memory_type?.type !== 'choice'
95
+ || answers.salience_band?.type !== 'score' || answers.contains_sensitive_material?.type !== 'noul') {
96
+ throw new Error('Malformed Jev response');
97
+ }
98
+ return {
99
+ shouldStore: finiteProbability(answers.should_store.noul, 'should_store'),
100
+ memoryType: memoryType(answers.memory_type.choice),
101
+ memoryTypeConfidence: finiteProbability(answers.memory_type.confidence, 'memory_type confidence'),
102
+ salienceBand: salienceBand(answers.salience_band.score),
103
+ provider: 'jev',
104
+ containsSensitiveMaterial: finiteProbability(answers.contains_sensitive_material.noul, 'contains_sensitive_material'),
105
+ };
106
+ }
107
+ finally {
108
+ clearTimeout(timer);
109
+ }
110
+ }
111
+ }
112
+ function requestedMode(env) {
113
+ const value = env.HUMEMORY_JEV_MODE?.trim().toLowerCase();
114
+ return value === 'shadow' || value === 'advisory' ? value : 'off';
115
+ }
116
+ /** API-key presence alone is inert. Advisory is deliberately capped to shadow. */
117
+ export function resolveConfiguredJevAdvisor(env = process.env, fetchImpl) {
118
+ const requested = requestedMode(env);
119
+ if (requested === 'off')
120
+ return { requestedMode: requested, effectiveMode: 'off' };
121
+ const apiKey = env.TYPESAFE_API_KEY?.trim();
122
+ if (!apiKey) {
123
+ return {
124
+ requestedMode: requested,
125
+ effectiveMode: 'shadow',
126
+ unavailableReason: 'missing_api_key',
127
+ };
128
+ }
129
+ return {
130
+ requestedMode: requested,
131
+ effectiveMode: 'shadow',
132
+ advisor: new JevMemoryAdvisor({
133
+ apiKey,
134
+ model: env.HUMEMORY_JEV_MODEL?.trim() || 'jev-latest',
135
+ timeoutMs: Number(env.HUMEMORY_JEV_TIMEOUT_MS ?? 3_000),
136
+ fetch: fetchImpl,
137
+ }),
138
+ };
139
+ }
@@ -1,5 +1,6 @@
1
1
  import { rename } from 'fs/promises';
2
2
  import type { LLMClient } from '../core/llm-generator.js';
3
+ import type { MemoryAdvisor, ShadowDecisionReporter } from './memory-advisor.js';
3
4
  export interface MaintenanceJob {
4
5
  version: 1;
5
6
  id: string;
@@ -34,6 +35,8 @@ export interface WorkerOptions {
34
35
  queueDir: string;
35
36
  dbPath: string;
36
37
  client?: LLMClient;
38
+ memoryAdvisor?: MemoryAdvisor;
39
+ advisorReporter?: ShadowDecisionReporter;
37
40
  llmTimeoutMs?: number;
38
41
  maxJobs?: number;
39
42
  maxAttempts?: number;
@@ -221,6 +221,8 @@ export async function processMaintenanceQueue(options) {
221
221
  directory: job.directory,
222
222
  maxLearnings: job.maxLearnings,
223
223
  client: options.client,
224
+ memoryAdvisor: options.memoryAdvisor,
225
+ advisorReporter: options.advisorReporter,
224
226
  llmTimeoutMs: options.llmTimeoutMs,
225
227
  source: 'hook',
226
228
  agent: job.agent,
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import type { LLMClient } from '../core/llm-generator.js';
17
17
  import type { Clock } from '../core/clock.js';
18
+ import { type MemoryAdvisor, type ShadowDecisionReporter } from './memory-advisor.js';
18
19
  import { type WorkerResult } from './maintenance-queue.js';
19
20
  import { type CodexImportResult } from './codex-import.js';
20
21
  import { type KimiImportResult } from './kimi-import.js';
@@ -38,6 +39,9 @@ export interface MaintenancePassOptions {
38
39
  opencodeRun?: OpenCodeCommandRunner;
39
40
  opencodeCommand?: string;
40
41
  client?: LLMClient;
42
+ /** `false` is an explicit test/operator override even when env selects shadow mode. */
43
+ memoryAdvisor?: MemoryAdvisor | false;
44
+ advisorReporter?: ShadowDecisionReporter;
41
45
  llmTimeoutMs?: number;
42
46
  maxJobs?: number;
43
47
  clock?: Clock;
@@ -55,14 +59,20 @@ export interface MaintenancePassResult {
55
59
  }
56
60
  export declare function defaultQueueDir(): string;
57
61
  export declare function defaultDbPath(): string;
58
- export declare function defaultLlmTimeoutMs(): number;
62
+ export declare function defaultLlmTimeoutMs(dbPath?: string): number;
59
63
  export declare function configuredIntervalMs(): number;
60
64
  /**
61
65
  * The LLM the pass consolidates with. 'none' (the default) keeps consolidation
62
66
  * deterministic and network-free; there is no API key on the production machine
63
- * and none wanted, so 'codex' shells out to the logged-in CLI instead.
67
+ * and none wanted, so CLI providers use the logged-in subscription instead.
68
+ * Local provider settings require enabled=true; an environment override remains explicit.
64
69
  */
65
- export declare function resolveMaintenanceClient(timeoutMs?: number): Promise<LLMClient | undefined>;
70
+ export declare function resolveMaintenanceClient(timeoutMs?: number | undefined, dbPath?: string, queueDir?: string): Promise<LLMClient | undefined>;
71
+ /** Resolve Jev only at executable entry points, never inside the hermetic pass. */
72
+ export declare function resolveMaintenanceAdvisor(dbPath?: string): {
73
+ memoryAdvisor?: MemoryAdvisor;
74
+ advisorReporter?: ShadowDecisionReporter;
75
+ };
66
76
  /**
67
77
  * Import, then drain, then record. Every producer is isolated: a missing or
68
78
  * unreadable runtime must never stall the queue or another producer.
@@ -13,11 +13,15 @@
13
13
  * it succeeds or fails, so a loop that has silently stopped is detectable from
14
14
  * the CLI and the API instead of being noticed weeks later.
15
15
  */
16
- import { dirname } from 'path';
16
+ import { dirname, join } from 'path';
17
17
  import { fileURLToPath } from 'url';
18
+ import { readFileSync } from 'fs';
18
19
  import { systemClock } from '../core/clock.js';
19
20
  import { databasePath, queueDirectory } from '../core/paths.js';
20
21
  import { createCodexClient } from '../core/llm-cli-client.js';
22
+ import { createKimiClient } from '../core/kimi-llm-client.js';
23
+ import { resolveConfiguredJevAdvisor } from './jev-advisor.js';
24
+ import { jsonlShadowReporter, } from './memory-advisor.js';
21
25
  import { processMaintenanceQueue } from './maintenance-queue.js';
22
26
  import { importCodexRollouts, defaultCodexSessionsDir } from './codex-import.js';
23
27
  import { importKimiSessions, defaultKimiHome } from './kimi-import.js';
@@ -31,8 +35,18 @@ export function defaultQueueDir() {
31
35
  export function defaultDbPath() {
32
36
  return databasePath();
33
37
  }
34
- export function defaultLlmTimeoutMs() {
35
- return Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000);
38
+ function localLlmConfiguration(dbPath = defaultDbPath()) {
39
+ try {
40
+ return JSON.parse(readFileSync(join(dirname(dbPath), 'maintenance-llm.json'), 'utf8'));
41
+ }
42
+ catch (e) {
43
+ if (e.code === 'ENOENT')
44
+ return {};
45
+ throw e;
46
+ }
47
+ }
48
+ export function defaultLlmTimeoutMs(dbPath = defaultDbPath()) {
49
+ return Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? localLlmConfiguration(dbPath).timeoutMs ?? 8_000);
36
50
  }
37
51
  export function configuredIntervalMs() {
38
52
  const raw = Number(process.env.HUMEMORY_MAINTENANCE_INTERVAL_MS ?? DEFAULT_INTERVAL_MS);
@@ -41,10 +55,13 @@ export function configuredIntervalMs() {
41
55
  /**
42
56
  * The LLM the pass consolidates with. 'none' (the default) keeps consolidation
43
57
  * deterministic and network-free; there is no API key on the production machine
44
- * and none wanted, so 'codex' shells out to the logged-in CLI instead.
58
+ * and none wanted, so CLI providers use the logged-in subscription instead.
59
+ * Local provider settings require enabled=true; an environment override remains explicit.
45
60
  */
46
- export async function resolveMaintenanceClient(timeoutMs = defaultLlmTimeoutMs()) {
47
- const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? 'none';
61
+ export async function resolveMaintenanceClient(timeoutMs = undefined, dbPath = defaultDbPath(), queueDir = defaultQueueDir()) {
62
+ const config = localLlmConfiguration(dbPath);
63
+ const timeout = timeoutMs ?? defaultLlmTimeoutMs(dbPath);
64
+ const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? (config.enabled === true ? config.provider : 'none') ?? 'none';
48
65
  if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
49
66
  const { default: Anthropic } = await import('@anthropic-ai/sdk');
50
67
  return new Anthropic();
@@ -52,10 +69,25 @@ export async function resolveMaintenanceClient(timeoutMs = defaultLlmTimeoutMs()
52
69
  if (provider === 'codex') {
53
70
  // No API key needed: the logged-in `codex` CLI answers instead. Slower than
54
71
  // an SDK call (agent start-up), so it gets its own, larger budget.
55
- return createCodexClient({ timeoutMs });
72
+ return createCodexClient({ timeoutMs: timeout });
73
+ }
74
+ if (provider === 'kimi') {
75
+ return createKimiClient({ model: process.env.HUMEMORY_LLM_MODEL ?? config.model ?? 'kimi-code/k3-256k',
76
+ timeoutMs: Math.min(timeout, 60_000), statePath: join(dirname(dbPath), 'kimi-llm-budget.json'), queueDir,
77
+ maxCallsPerDay: config.maxCallsPerDay ?? 2, quotaStopPercent: config.quotaStopPercent ?? 24 });
56
78
  }
57
79
  return undefined;
58
80
  }
81
+ /** Resolve Jev only at executable entry points, never inside the hermetic pass. */
82
+ export function resolveMaintenanceAdvisor(dbPath = defaultDbPath()) {
83
+ const configured = resolveConfiguredJevAdvisor();
84
+ if (!configured.advisor)
85
+ return {};
86
+ return {
87
+ memoryAdvisor: configured.advisor,
88
+ advisorReporter: jsonlShadowReporter(join(dirname(dbPath), 'jev-shadow.jsonl')),
89
+ };
90
+ }
59
91
  /**
60
92
  * Import, then drain, then record. Every producer is isolated: a missing or
61
93
  * unreadable runtime must never stall the queue or another producer.
@@ -68,11 +100,15 @@ export async function runMaintenancePass(options = {}) {
68
100
  const queueDir = options.queueDir ?? defaultQueueDir();
69
101
  const dbPath = options.dbPath ?? defaultDbPath();
70
102
  const statePath = options.statePath ?? defaultStatePath(queueDir);
71
- const llmTimeoutMs = options.llmTimeoutMs ?? defaultLlmTimeoutMs();
103
+ const llmTimeoutMs = options.llmTimeoutMs ?? defaultLlmTimeoutMs(dbPath);
72
104
  const codexSinceDays = options.codexSinceDays ?? 1;
73
105
  const kimiSinceDays = options.kimiSinceDays ?? 1;
74
106
  const opencodeSinceDays = options.opencodeSinceDays ?? 1;
75
107
  const startedAt = clock.now();
108
+ // No environment lookup here. Tests and library callers get a hermetic pass
109
+ // unless an executable entry point injects an advisor.
110
+ const memoryAdvisor = options.memoryAdvisor === false ? undefined : options.memoryAdvisor;
111
+ const advisorReporter = options.advisorReporter;
76
112
  let codex;
77
113
  let codexError;
78
114
  if (codexSinceDays !== false) {
@@ -124,6 +160,8 @@ export async function runMaintenancePass(options = {}) {
124
160
  queueDir,
125
161
  dbPath,
126
162
  client: options.client,
163
+ memoryAdvisor,
164
+ advisorReporter,
127
165
  llmTimeoutMs,
128
166
  maxJobs: options.maxJobs ?? Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
129
167
  now: () => clock.now(),
@@ -206,8 +244,20 @@ export function startMaintenanceLoop(options = {}) {
206
244
  return;
207
245
  running = true;
208
246
  try {
209
- const client = options.client ?? await resolveMaintenanceClient(options.llmTimeoutMs);
210
- const { worker } = await runMaintenancePass({ ...options, client, runner: options.runner ?? 'api-loop' });
247
+ const client = options.client ?? await resolveMaintenanceClient(options.llmTimeoutMs, options.dbPath ?? defaultDbPath(), options.queueDir ?? defaultQueueDir());
248
+ // The resident API loop is an executable entry point, so it may resolve
249
+ // the opt-in provider. `runMaintenancePass` itself remains environment-free.
250
+ const advisor = options.memoryAdvisor === false
251
+ ? {}
252
+ : options.memoryAdvisor
253
+ ? { memoryAdvisor: options.memoryAdvisor, advisorReporter: options.advisorReporter }
254
+ : resolveMaintenanceAdvisor(options.dbPath ?? defaultDbPath());
255
+ const { worker } = await runMaintenancePass({
256
+ ...options,
257
+ ...advisor,
258
+ client,
259
+ runner: options.runner ?? 'api-loop',
260
+ });
211
261
  if (process.env.HUMEMORY_VERBOSE === '1' || worker.failed > 0) {
212
262
  console.error(`[humemory] maintenance: ${worker.processed}/${worker.discovered} jobs, ` +
213
263
  `${worker.memoriesStored} memories, ${worker.failed} failed, ${worker.deadLettered} dead-lettered` +
@@ -0,0 +1,86 @@
1
+ import type { MemoryType, TraceSource } from '../core/types.js';
2
+ /**
3
+ * Acquisition-side advice contract.
4
+ *
5
+ * This module owns the local privacy gate and shadow reporting. It does not
6
+ * own storage policy: while shadow mode is active, callers keep the baseline
7
+ * learning even when the provider disagrees or fails.
8
+ */
9
+ export declare const SALIENCE_BANDS: readonly ["discard", "low", "normal", "high", "exceptional"];
10
+ export type SalienceBand = typeof SALIENCE_BANDS[number];
11
+ export interface MemoryAdvice {
12
+ shouldStore: number;
13
+ memoryType: MemoryType;
14
+ memoryTypeConfidence: number | null;
15
+ salienceBand: SalienceBand;
16
+ provider: 'jev';
17
+ /** Experimental signal only. Privacy has already been decided locally. */
18
+ containsSensitiveMaterial?: number;
19
+ }
20
+ export interface SanitizedMemoryCandidate {
21
+ content: string;
22
+ currentMemoryType: MemoryType;
23
+ source: TraceSource;
24
+ truncated: boolean;
25
+ redactions: Array<'path' | 'identity' | 'command_output'>;
26
+ }
27
+ /** Provider-neutral seam. Implementations only receive locally approved text. */
28
+ export interface MemoryAdvisor {
29
+ advise(candidate: SanitizedMemoryCandidate): Promise<MemoryAdvice>;
30
+ }
31
+ export interface AutomaticMemoryCandidate {
32
+ content: string;
33
+ currentMemoryType: MemoryType;
34
+ source: TraceSource;
35
+ }
36
+ export type CandidateRejectionReason = 'source_not_allowed' | 'sensitive_material' | 'empty_after_redaction';
37
+ export type CandidateSanitization = {
38
+ accepted: true;
39
+ hash: string;
40
+ candidate: SanitizedMemoryCandidate;
41
+ } | {
42
+ accepted: false;
43
+ hash: string;
44
+ reason: CandidateRejectionReason;
45
+ };
46
+ export interface SanitizeCandidateOptions {
47
+ maxCharacters?: number;
48
+ allowedSources?: ReadonlySet<TraceSource>;
49
+ }
50
+ /**
51
+ * Apply the local privacy gate before provider code can run.
52
+ *
53
+ * Known credentials reject the whole candidate. Paths and machine identities
54
+ * can be removed safely, so they are replaced before the character cap is
55
+ * applied. Human-authored memories are outside this automatic path.
56
+ */
57
+ export declare function sanitizeMemoryCandidate(input: AutomaticMemoryCandidate, options?: SanitizeCandidateOptions): CandidateSanitization;
58
+ /** Keep provider output on a fixed local scale; Jev never writes a raw salience value. */
59
+ export declare function salienceForBand(band: SalienceBand): number;
60
+ /** Safe-to-persist comparison metadata. Candidate text is absent by design. */
61
+ export interface ShadowDecisionRecord {
62
+ at: string;
63
+ mode: 'shadow';
64
+ candidateHash: string;
65
+ source: TraceSource;
66
+ baseline: {
67
+ shouldStore: true;
68
+ memoryType: MemoryType;
69
+ };
70
+ outcome: 'advised' | 'rejected' | 'failed';
71
+ latencyMs: number;
72
+ rejectionReason?: CandidateRejectionReason;
73
+ errorKind?: 'provider_failure';
74
+ advice?: MemoryAdvice & {
75
+ mappedSaillance: number;
76
+ };
77
+ }
78
+ export type ShadowDecisionReporter = (record: ShadowDecisionRecord) => void | Promise<void>;
79
+ /**
80
+ * Compare one automatic candidate with the advisor without changing the
81
+ * candidate or throwing into maintenance. The return value is for tests and
82
+ * reporting; it never controls whether the baseline learning is stored.
83
+ */
84
+ export declare function adviseInShadow(input: AutomaticMemoryCandidate, advisor: MemoryAdvisor, reporter?: ShadowDecisionReporter, now?: () => Date): Promise<ShadowDecisionRecord>;
85
+ /** Append metadata only; `ShadowDecisionRecord` has no field for candidate text. */
86
+ export declare function jsonlShadowReporter(path: string): ShadowDecisionReporter;