humemory 0.2.4 → 0.2.5

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,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.5] - 2026-08-26
4
+ **Features:**
5
+ - ingest codex sessions, not just claude ones
6
+ - consolidate through the codex CLI, no API key
7
+
8
+ **Bug Fixes:**
9
+ - date a trace on the session's clock, not the sweep's
10
+
11
+ **Documentation:**
12
+ - document codex rollout import
13
+
14
+
15
+
3
16
  ## [0.2.4] - 2026-08-23
4
17
  **Bug Fixes:**
5
18
  - stop returning internal error detail to clients (L-01)
package/README.md CHANGED
@@ -96,6 +96,28 @@ An entry means **ready to be discovered**, not that its evolving private session
96
96
  format is already parsed. Run `pnpm cli sources discover --installed-only` for a
97
97
  local inventory without exposing conversation content.
98
98
 
99
+ **Codex is parsed.** Its rollouts (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`,
100
+ `$CODEX_HOME` honoured) import into the same queue the agent hooks write to:
101
+
102
+ ```bash
103
+ pnpm cli sources import-codex --dry-run # what would be queued, writes nothing
104
+ pnpm cli sources import-codex --since 7 # the last week (default)
105
+ pnpm cli sources import-codex --all # every rollout ever recorded
106
+ ```
107
+
108
+ Importing only *queues*; the worker still decides what becomes a trace. Jobs are
109
+ keyed on session, so re-importing is idempotent and a thread that grew since the
110
+ last pass contributes only its new messages. Threads codex spawned for itself
111
+ (judges, reviews) are excluded unless `--include-subagents` — they are not
112
+ sessions a human had. Model reasoning and tool calls are dropped like
113
+ `tool_result` already is: a learning is what was decided, not how it was found.
114
+
115
+ A trace is dated on the transcript's own clock, not on the sweep's: a rollout
116
+ read three weeks late encodes on the day it was lived, and arrives already
117
+ degraded to the level that age warrants. Without this a bulk import collapses
118
+ every session into a single import day, and the store loses the timeline that
119
+ `day` exists to hold.
120
+
99
121
  The React app is served at **`/`** (and `/app`). The original vanilla dashboard
100
122
  has been removed — the React front reached parity first, and git keeps the old
101
123
  one if it is ever needed.
@@ -198,6 +220,15 @@ Claude as an asynchronous quality enhancement, set
198
220
  timeouts fall back to the deterministic extractor. A queue item is deleted only
199
221
  after its extracted memories are committed successfully.
200
222
 
223
+ Without an API key, `HUMEMORY_MAINTENANCE_LLM=codex` uses the logged-in `codex`
224
+ CLI instead — same fallback, no key, your agent subscription pays. Raise
225
+ `HUMEMORY_MAINTENANCE_TIMEOUT_MS` to ~60000: an agent turn costs seconds of
226
+ start-up before the first token. The adapter runs codex `--ephemeral` and
227
+ `--ignore-user-config` deliberately: a persisted rollout would be re-ingested as
228
+ a trace later, and a humemory hook wired into codex would re-enter humemory
229
+ mid-maintenance. Expect ~12k tokens of agent preamble per call regardless of
230
+ trace size — this buys summary quality, not economy.
231
+
201
232
  The queue directory is the whole contract, and it is inspectable at any time:
202
233
 
203
234
  | Entry | Meaning |
@@ -212,8 +243,9 @@ The queue directory is the whole contract, and it is inspectable at any time:
212
243
  | --- | --- | --- |
213
244
  | `HUMEMORY_DB` | `data/humemory.db` | database path |
214
245
  | `HUMEMORY_QUEUE` | `data/maintenance-queue` | durable raw-session inbox |
215
- | `HUMEMORY_MAINTENANCE_LLM` | `none` | optional enhancement (`anthropic`) |
216
- | `HUMEMORY_MAINTENANCE_TIMEOUT_MS` | `8000` | model timeout; never affects the agent hook |
246
+ | `HUMEMORY_MAINTENANCE_LLM` | `none` | optional enhancement (`anthropic`, `codex`) |
247
+ | `HUMEMORY_MAINTENANCE_TIMEOUT_MS` | `8000` | model timeout; never affects the agent hook. `codex` needs ~60000 |
248
+ | `HUMEMORY_LLM_MODEL` | provider default | model id; mini models are rejected on ChatGPT accounts |
217
249
  | `HUMEMORY_DIR` | `cwd` | mental place to scope loops and traces to |
218
250
  | `HUMEMORY_SESSION_BUDGET` | `10` | max items listed per section |
219
251
  | `HUMEMORY_SAILLANCE_MIN` | `60` | salience floor for recalling a decayed trace |
@@ -1,5 +1,5 @@
1
1
  import { SQLiteStore } from '../store/sqlite.js';
2
- import { parseClaudeHookPayload } from './session-parser.js';
2
+ import { lastMessageTime, parseAgentSession } from './session-parser.js';
3
3
  import { extractLearnings, extractLearningsDeterministic } from './learning-extractor.js';
4
4
  async function withTimeout(promise, timeoutMs) {
5
5
  let timer;
@@ -18,7 +18,7 @@ async function withTimeout(promise, timeoutMs) {
18
18
  }
19
19
  export async function processSession(rawTranscript, options) {
20
20
  const directory = options.directory ?? process.cwd();
21
- const session = parseClaudeHookPayload(rawTranscript, directory);
21
+ const session = parseAgentSession(rawTranscript, directory);
22
22
  const maxLearnings = options.maxLearnings ?? 5;
23
23
  const messagesSeen = session.messages.length;
24
24
  // Only the messages added since the last successful pass are candidates.
@@ -49,6 +49,10 @@ export async function processSession(rawTranscript, options) {
49
49
  if (learnings.length === 0) {
50
50
  return { sessionId: session.sessionId, directory: session.directory, memoriesStored: 0, learnings: [], extractionMode, messagesSeen };
51
51
  }
52
+ // What is encoded belongs to the day the session ran, not the day it was
53
+ // read: a rollout sweep runs long after the fact, and dating every trace on
54
+ // the sweep collapses the timeline into a single import day.
55
+ const occurredAt = lastMessageTime(pending) ?? session.occurredAt ?? new Date();
52
56
  const store = new SQLiteStore(options.dbPath);
53
57
  const stored = [];
54
58
  try {
@@ -56,7 +60,8 @@ export async function processSession(rawTranscript, options) {
56
60
  await store.add({
57
61
  content: learning.content,
58
62
  directory: session.directory,
59
- day: new Date().toISOString().split('T')[0],
63
+ day: occurredAt.toISOString().split('T')[0],
64
+ createdAt: occurredAt,
60
65
  keywords: learning.keywords,
61
66
  sessionId: session.sessionId,
62
67
  memoryType: learning.memoryType,
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Imports Codex CLI rollouts into the maintenance queue.
3
+ *
4
+ * Acquisition stays outside the cognitive core: this only decides *which files
5
+ * are candidate sessions* and hands their raw bytes to `enqueueSession`. What
6
+ * becomes a trace, how it decays and when it resurfaces is still the store's
7
+ * business, decided later by the worker — the same path a Claude `Stop` hook
8
+ * feeds.
9
+ *
10
+ * Re-importing is safe: a queue job is keyed on `source + sessionId`, and the
11
+ * worker keeps a per-session checkpoint, so a rollout that grew since the last
12
+ * pass contributes only its new messages.
13
+ */
14
+ /** Marks these jobs as coming from a rollout sweep rather than a live hook. */
15
+ export declare const CODEX_SOURCE = "codex-rollout";
16
+ export interface CodexImportOptions {
17
+ queueDir: string;
18
+ /** Defaults to `$CODEX_HOME/sessions`, else `~/.codex/sessions`. */
19
+ sessionsDir?: string;
20
+ /** Only rollouts modified at or after this instant. */
21
+ since?: Date;
22
+ /** Stop after this many *queued* sessions. */
23
+ limit?: number;
24
+ /** Threads Codex spawned for itself (judges, reviews) are excluded by default. */
25
+ includeSubagents?: boolean;
26
+ /** Scan and report without writing to the queue. */
27
+ dryRun?: boolean;
28
+ maxLearnings?: number;
29
+ }
30
+ export interface CodexImportResult {
31
+ scanned: number;
32
+ queued: number;
33
+ created: number;
34
+ skippedSubagent: number;
35
+ skippedEmpty: number;
36
+ skippedOld: number;
37
+ unreadable: number;
38
+ }
39
+ export declare function defaultCodexSessionsDir(): string;
40
+ export declare function importCodexRollouts(options: CodexImportOptions): Promise<CodexImportResult>;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Imports Codex CLI rollouts into the maintenance queue.
3
+ *
4
+ * Acquisition stays outside the cognitive core: this only decides *which files
5
+ * are candidate sessions* and hands their raw bytes to `enqueueSession`. What
6
+ * becomes a trace, how it decays and when it resurfaces is still the store's
7
+ * business, decided later by the worker — the same path a Claude `Stop` hook
8
+ * feeds.
9
+ *
10
+ * Re-importing is safe: a queue job is keyed on `source + sessionId`, and the
11
+ * worker keeps a per-session checkpoint, so a rollout that grew since the last
12
+ * pass contributes only its new messages.
13
+ */
14
+ import { readdir, readFile, stat } from 'fs/promises';
15
+ import { homedir } from 'os';
16
+ import { join } from 'path';
17
+ import { enqueueSession } from './maintenance-queue.js';
18
+ import { isSubagentThread, parseCodexRollout, readCodexRolloutMeta } from './codex-rollout-parser.js';
19
+ /** Marks these jobs as coming from a rollout sweep rather than a live hook. */
20
+ export const CODEX_SOURCE = 'codex-rollout';
21
+ export function defaultCodexSessionsDir() {
22
+ const home = process.env.CODEX_HOME ?? join(homedir(), '.codex');
23
+ return join(home, 'sessions');
24
+ }
25
+ /** Rollout files, depth-first through the YYYY/MM/DD tree. */
26
+ async function findRollouts(dir) {
27
+ let entries;
28
+ try {
29
+ entries = await readdir(dir, { withFileTypes: true });
30
+ }
31
+ catch {
32
+ return []; // No codex on this machine, or no session ever recorded.
33
+ }
34
+ const found = [];
35
+ for (const entry of entries) {
36
+ const path = join(dir, entry.name);
37
+ if (entry.isDirectory())
38
+ found.push(...(await findRollouts(path)));
39
+ else if (entry.name.startsWith('rollout-') && entry.name.endsWith('.jsonl'))
40
+ found.push(path);
41
+ }
42
+ return found;
43
+ }
44
+ export async function importCodexRollouts(options) {
45
+ const sessionsDir = options.sessionsDir ?? defaultCodexSessionsDir();
46
+ const result = {
47
+ scanned: 0, queued: 0, created: 0,
48
+ skippedSubagent: 0, skippedEmpty: 0, skippedOld: 0, unreadable: 0,
49
+ };
50
+ const files = (await findRollouts(sessionsDir)).sort();
51
+ for (const file of files) {
52
+ if (options.limit !== undefined && result.queued >= options.limit)
53
+ break;
54
+ result.scanned += 1;
55
+ try {
56
+ if (options.since) {
57
+ const { mtime } = await stat(file);
58
+ if (mtime < options.since) {
59
+ result.skippedOld += 1;
60
+ continue;
61
+ }
62
+ }
63
+ const raw = await readFile(file, 'utf-8');
64
+ const meta = readCodexRolloutMeta(raw);
65
+ if (!options.includeSubagents && isSubagentThread(meta)) {
66
+ result.skippedSubagent += 1;
67
+ continue;
68
+ }
69
+ // A rollout with no human turn and no answer holds nothing to learn from:
70
+ // an aborted start, or a thread that only ran tools.
71
+ const parsed = parseCodexRollout(raw, meta?.directory ?? sessionsDir);
72
+ if (parsed.messages.length === 0) {
73
+ result.skippedEmpty += 1;
74
+ continue;
75
+ }
76
+ if (options.dryRun) {
77
+ result.queued += 1;
78
+ continue;
79
+ }
80
+ const { created } = await enqueueSession(raw, {
81
+ queueDir: options.queueDir,
82
+ directory: parsed.directory,
83
+ source: CODEX_SOURCE,
84
+ agent: 'codex',
85
+ maxLearnings: options.maxLearnings,
86
+ });
87
+ result.queued += 1;
88
+ if (created)
89
+ result.created += 1;
90
+ }
91
+ catch {
92
+ // A rollout being written to, or one this user cannot read: never fatal.
93
+ result.unreadable += 1;
94
+ }
95
+ }
96
+ return result;
97
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Parses a Codex CLI rollout into the same `ParsedSession` the Claude hook produces.
3
+ *
4
+ * Codex persists one JSONL file per thread under
5
+ * `~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<id>.jsonl`. Every line is an
6
+ * envelope `{ timestamp, type, payload }`; only two types carry a conversation:
7
+ *
8
+ * session_meta — first line: session id, cwd, and the thread's provenance
9
+ * response_item — the turns, of which only `payload.type === 'message'` is one
10
+ *
11
+ * `reasoning`, `custom_tool_call` and `custom_tool_call_output` items are
12
+ * dropped: the first is model-internal, the others are tool plumbing. The
13
+ * Claude parser drops `tool_result` for the same reason — a learning comes from
14
+ * what was decided, not from the mechanics of getting there.
15
+ */
16
+ import { type ParsedSession } from './session-parser.js';
17
+ export interface CodexRolloutMeta {
18
+ sessionId: string;
19
+ directory?: string;
20
+ /** `user` for a thread you typed into, `subagent` for one Codex spawned itself. */
21
+ threadSource?: string;
22
+ timestamp?: string;
23
+ }
24
+ /** Reads the provenance header without walking the whole transcript. */
25
+ export declare function readCodexRolloutMeta(raw: string): CodexRolloutMeta | null;
26
+ /** True when this text is a Codex rollout rather than a Claude hook payload. */
27
+ export declare function isCodexRollout(raw: string): boolean;
28
+ /** A thread Codex spawned for itself — judge passes, reviews — is not a lived session. */
29
+ export declare function isSubagentThread(meta: CodexRolloutMeta | null): boolean;
30
+ export declare function parseCodexRollout(raw: string, directory: string): ParsedSession;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Parses a Codex CLI rollout into the same `ParsedSession` the Claude hook produces.
3
+ *
4
+ * Codex persists one JSONL file per thread under
5
+ * `~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<id>.jsonl`. Every line is an
6
+ * envelope `{ timestamp, type, payload }`; only two types carry a conversation:
7
+ *
8
+ * session_meta — first line: session id, cwd, and the thread's provenance
9
+ * response_item — the turns, of which only `payload.type === 'message'` is one
10
+ *
11
+ * `reasoning`, `custom_tool_call` and `custom_tool_call_output` items are
12
+ * dropped: the first is model-internal, the others are tool plumbing. The
13
+ * Claude parser drops `tool_result` for the same reason — a learning comes from
14
+ * what was decided, not from the mechanics of getting there.
15
+ */
16
+ import { lastMessageTime } from './session-parser.js';
17
+ /**
18
+ * Turns Codex injects into the user side of the transcript: they are context,
19
+ * not something a human said, and encoding them would fill the memory with
20
+ * plugin catalogues and environment dumps.
21
+ */
22
+ const INJECTED_USER_BLOCK = /^<(environment_context|recommended_plugins|user_instructions|instructions|skills?_context)>/;
23
+ function textOf(content) {
24
+ if (typeof content === 'string')
25
+ return content;
26
+ if (!Array.isArray(content))
27
+ return '';
28
+ return content
29
+ .map((block) => (block?.type === 'input_text' || block?.type === 'output_text' ? (block.text ?? '') : ''))
30
+ .filter(Boolean)
31
+ .join('\n');
32
+ }
33
+ function lines(raw) {
34
+ const parsed = [];
35
+ for (const line of raw.split('\n')) {
36
+ if (!line.trim())
37
+ continue;
38
+ try {
39
+ parsed.push(JSON.parse(line));
40
+ }
41
+ catch {
42
+ // A rollout being written to is legitimately truncated on its last line.
43
+ }
44
+ }
45
+ return parsed;
46
+ }
47
+ /** Reads the provenance header without walking the whole transcript. */
48
+ export function readCodexRolloutMeta(raw) {
49
+ for (const entry of lines(raw)) {
50
+ if (entry?.type !== 'session_meta')
51
+ continue;
52
+ const payload = entry.payload ?? {};
53
+ return {
54
+ sessionId: payload.session_id ?? payload.id ?? '',
55
+ directory: typeof payload.cwd === 'string' ? payload.cwd : undefined,
56
+ threadSource: payload.thread_source,
57
+ timestamp: payload.timestamp ?? entry.timestamp,
58
+ };
59
+ }
60
+ return null;
61
+ }
62
+ /** True when this text is a Codex rollout rather than a Claude hook payload. */
63
+ export function isCodexRollout(raw) {
64
+ const first = raw.split('\n').find((line) => line.trim());
65
+ if (!first)
66
+ return false;
67
+ try {
68
+ const entry = JSON.parse(first);
69
+ return entry?.type === 'session_meta' || entry?.type === 'response_item';
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
75
+ /** A thread Codex spawned for itself — judge passes, reviews — is not a lived session. */
76
+ export function isSubagentThread(meta) {
77
+ return meta?.threadSource === 'subagent';
78
+ }
79
+ export function parseCodexRollout(raw, directory) {
80
+ const entries = lines(raw);
81
+ const meta = readCodexRolloutMeta(raw);
82
+ const messages = [];
83
+ for (const entry of entries) {
84
+ if (entry?.type !== 'response_item')
85
+ continue;
86
+ const payload = entry.payload ?? {};
87
+ if (payload.type !== 'message')
88
+ continue;
89
+ // `developer` carries the base instructions, not a turn.
90
+ if (payload.role !== 'user' && payload.role !== 'assistant')
91
+ continue;
92
+ const content = textOf(payload.content).trim();
93
+ if (!content)
94
+ continue;
95
+ if (payload.role === 'user' && INJECTED_USER_BLOCK.test(content))
96
+ continue;
97
+ messages.push({ role: payload.role, content, timestamp: entry.timestamp });
98
+ }
99
+ // A sweep can read a rollout weeks after the thread ran: the transcript's own
100
+ // clock is what the trace must be dated by, not the moment of the sweep.
101
+ const metaTime = meta?.timestamp ? new Date(meta.timestamp) : undefined;
102
+ const occurredAt = lastMessageTime(messages) ??
103
+ (metaTime && !Number.isNaN(metaTime.getTime()) ? metaTime : undefined);
104
+ return {
105
+ sessionId: meta?.sessionId || `codex-${Date.now()}`,
106
+ directory: meta?.directory || directory,
107
+ messages,
108
+ occurredAt,
109
+ rawText: messages.map((m) => `${m.role}: ${m.content}`).join('\n\n'),
110
+ };
111
+ }
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from 'crypto';
2
2
  import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'fs/promises';
3
3
  import { join } from 'path';
4
4
  import { processSession } from './claude-hook.js';
5
- import { parseClaudeHookPayload } from './session-parser.js';
5
+ import { parseAgentSession } from './session-parser.js';
6
6
  const DEFAULT_LOCK_STALE_MS = 5 * 60 * 1000;
7
7
  const DEFAULT_MAX_ATTEMPTS = 5;
8
8
  const DEAD_LETTER_SUFFIX = '.dead.json';
@@ -40,7 +40,7 @@ export async function enqueueSession(rawTranscript, options) {
40
40
  if (!raw)
41
41
  throw new Error('Cannot queue an empty session');
42
42
  const directory = options.directory ?? process.cwd();
43
- const parsed = parseClaudeHookPayload(rawTranscript, directory);
43
+ const parsed = parseAgentSession(rawTranscript, directory);
44
44
  const source = options.source ?? 'claude-code';
45
45
  // Keyed on session, not transcript content: `Stop` fires once per turn and the
46
46
  // transcript grows each time, so hashing the raw text would enqueue one job
@@ -8,5 +8,22 @@ export interface ParsedSession {
8
8
  directory: string;
9
9
  messages: SessionMessage[];
10
10
  rawText: string;
11
+ /**
12
+ * When the session was *lived*, not when it was read. A rollout swept weeks
13
+ * after the fact must encode as a trace of that day, otherwise every import
14
+ * lands on the import date and the memory loses its timeline — and, with it,
15
+ * the age decay works from.
16
+ */
17
+ occurredAt?: Date;
11
18
  }
19
+ /** The instant a transcript line carries, when it carries a usable one. */
20
+ export declare function messageTime(message: SessionMessage | undefined): Date | undefined;
21
+ /** The last usable instant in a run of messages — the session's own clock. */
22
+ export declare function lastMessageTime(messages: SessionMessage[]): Date | undefined;
12
23
  export declare function parseClaudeHookPayload(raw: string, directory: string): ParsedSession;
24
+ /**
25
+ * Entry point for any local agent transcript: detects the producer and hands
26
+ * off. Claude hook payloads and Codex rollouts are both JSON on stdin, so the
27
+ * dispatch is on shape, not on a flag the caller has to remember to pass.
28
+ */
29
+ export declare function parseAgentSession(raw: string, directory: string): ParsedSession;
@@ -1,3 +1,20 @@
1
+ import { isCodexRollout, parseCodexRollout } from './codex-rollout-parser.js';
2
+ /** The instant a transcript line carries, when it carries a usable one. */
3
+ export function messageTime(message) {
4
+ if (!message?.timestamp)
5
+ return undefined;
6
+ const at = new Date(message.timestamp);
7
+ return Number.isNaN(at.getTime()) ? undefined : at;
8
+ }
9
+ /** The last usable instant in a run of messages — the session's own clock. */
10
+ export function lastMessageTime(messages) {
11
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
12
+ const at = messageTime(messages[i]);
13
+ if (at)
14
+ return at;
15
+ }
16
+ return undefined;
17
+ }
1
18
  function extractText(content) {
2
19
  if (typeof content === 'string')
3
20
  return content;
@@ -33,6 +50,7 @@ export function parseClaudeHookPayload(raw, directory) {
33
50
  directory: payload.cwd ?? directory,
34
51
  messages,
35
52
  rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
53
+ occurredAt: lastMessageTime(messages),
36
54
  };
37
55
  }
38
56
  // Format: array of messages directly
@@ -47,6 +65,7 @@ export function parseClaudeHookPayload(raw, directory) {
47
65
  directory,
48
66
  messages,
49
67
  rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
68
+ occurredAt: lastMessageTime(messages),
50
69
  };
51
70
  }
52
71
  }
@@ -73,6 +92,7 @@ export function parseClaudeHookPayload(raw, directory) {
73
92
  directory,
74
93
  messages,
75
94
  rawText: messages.map(m => `${m.role}: ${m.content}`).join('\n\n'),
95
+ occurredAt: lastMessageTime(messages),
76
96
  };
77
97
  }
78
98
  // Fallback: plain text
@@ -83,3 +103,11 @@ export function parseClaudeHookPayload(raw, directory) {
83
103
  rawText: raw,
84
104
  };
85
105
  }
106
+ /**
107
+ * Entry point for any local agent transcript: detects the producer and hands
108
+ * off. Claude hook payloads and Codex rollouts are both JSON on stdin, so the
109
+ * dispatch is on shape, not on a flag the caller has to remember to pass.
110
+ */
111
+ export function parseAgentSession(raw, directory) {
112
+ return isCodexRollout(raw) ? parseCodexRollout(raw, directory) : parseClaudeHookPayload(raw, directory);
113
+ }
package/dist/cli/index.js CHANGED
@@ -12,6 +12,8 @@ const __dirname = dirname(__filename);
12
12
  // Shared store. HUMEMORY_DB points at another database — same convention as the
13
13
  // hooks, and required to exercise the CLI without touching production.
14
14
  const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
15
+ // Same inbox the agent hooks write to — the CLI only ever queues, never encodes.
16
+ const QUEUE_DIR = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
15
17
  let store;
16
18
  function getStore() {
17
19
  if (!store) {
@@ -794,6 +796,40 @@ for (const verb of ['approve', 'reject']) {
794
796
  const sources = program
795
797
  .command('sources')
796
798
  .description('Discover local AI agent runtimes without reading their sessions');
799
+ sources
800
+ .command('import-codex')
801
+ .description('Queue Codex CLI rollouts for maintenance (nothing is encoded until the worker runs)')
802
+ .option('--since <days>', 'Only rollouts touched in the last N days', '7')
803
+ .option('--all', 'Every rollout ever recorded, ignoring --since')
804
+ .option('--limit <n>', 'Stop after N queued sessions')
805
+ .option('--include-subagents', 'Also import threads codex spawned for itself')
806
+ .option('--dry-run', 'Report what would be queued, write nothing')
807
+ .option('--sessions-dir <dir>', 'Override $CODEX_HOME/sessions')
808
+ .action(async (options) => {
809
+ const { importCodexRollouts, defaultCodexSessionsDir } = await import('../agent/codex-import.js');
810
+ const sessionsDir = options.sessionsDir ? resolve(options.sessionsDir) : defaultCodexSessionsDir();
811
+ const days = Number(options.since);
812
+ const since = options.all || !Number.isFinite(days)
813
+ ? undefined
814
+ : new Date(Date.now() - days * 24 * 60 * 60 * 1000);
815
+ console.log(`⏳ Scanning ${sessionsDir}${since ? ` (last ${days} day(s))` : ' (all)'}...`);
816
+ const result = await importCodexRollouts({
817
+ queueDir: QUEUE_DIR,
818
+ sessionsDir,
819
+ since,
820
+ limit: options.limit ? parseInt(options.limit) : undefined,
821
+ includeSubagents: options.includeSubagents,
822
+ dryRun: options.dryRun,
823
+ });
824
+ console.log(`\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
825
+ `${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.`);
826
+ console.log(` skipped — ${result.skippedOld} older than the window, ` +
827
+ `${result.skippedSubagent} subagent thread(s), ${result.skippedEmpty} without a turn, ` +
828
+ `${result.unreadable} unreadable`);
829
+ if (!options.dryRun && result.queued > 0) {
830
+ console.log('\nRun `pnpm maintenance` to encode them (or wait for the scheduled pass).');
831
+ }
832
+ });
797
833
  sources
798
834
  .command('discover', { isDefault: true })
799
835
  .description('Show known runtimes and the local evidence found for each one')
@@ -0,0 +1,43 @@
1
+ /**
2
+ * `LLMClient` backed by a local agent CLI instead of a hosted API key.
3
+ *
4
+ * humemory's consolidation path is deterministic and network-free by default;
5
+ * this adapter exists for machines that have no `ANTHROPIC_API_KEY` but do have
6
+ * a logged-in coding agent on the PATH. It is opt-in
7
+ * (`HUMEMORY_MAINTENANCE_LLM=codex`) and every failure falls back to the
8
+ * deterministic extractor upstream, so a missing binary is never fatal.
9
+ *
10
+ * Three flags matter and none of them are cosmetic:
11
+ * --ephemeral no rollout is written under ~/.codex/sessions. Without
12
+ * it, each consolidation leaves a session that humemory
13
+ * would later ingest as a trace — memory eating itself.
14
+ * --ignore-user-config skips the user's skills, plugins and hooks. Cheaper
15
+ * (~2k fewer tokens per call, half the latency) and it
16
+ * stops a humemory Stop hook wired into codex from
17
+ * re-entering humemory while maintenance is running.
18
+ * -s read-only consolidation summarises text; it never needs a write.
19
+ */
20
+ import type { LLMClient } from './llm-generator.js';
21
+ /** Runs one non-interactive agent turn and resolves with its final message. */
22
+ export type CliRunner = (prompt: string, opts: {
23
+ timeoutMs: number;
24
+ }) => Promise<string>;
25
+ export interface CodexClientOptions {
26
+ /** Model id. Unset means the CLI's own default — mini models are rejected on ChatGPT accounts. */
27
+ model?: string;
28
+ /** Wall-clock budget for one turn. Agent start-up alone is several seconds. */
29
+ timeoutMs?: number;
30
+ /** Injected in tests; the default spawns the real `codex` binary. */
31
+ runner?: CliRunner;
32
+ }
33
+ /** Strips the ```json fences a chat-tuned model wraps around structured output. */
34
+ export declare function unfence(text: string): string;
35
+ /** Flattens an Anthropic-shaped request into one prompt string for a CLI turn. */
36
+ export declare function flattenPrompt(params: any): string;
37
+ export declare function codexArgs(outputPath: string, model?: string): string[];
38
+ /**
39
+ * Wraps a coding-agent CLI in the `LLMClient` shape the consolidation path expects.
40
+ * Only the fields `generateMemoryLevels` reads are honoured — this is a duck, not
41
+ * an SDK: no streaming, no tools, no token accounting.
42
+ */
43
+ export declare function createCodexClient(options?: CodexClientOptions): LLMClient;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * `LLMClient` backed by a local agent CLI instead of a hosted API key.
3
+ *
4
+ * humemory's consolidation path is deterministic and network-free by default;
5
+ * this adapter exists for machines that have no `ANTHROPIC_API_KEY` but do have
6
+ * a logged-in coding agent on the PATH. It is opt-in
7
+ * (`HUMEMORY_MAINTENANCE_LLM=codex`) and every failure falls back to the
8
+ * deterministic extractor upstream, so a missing binary is never fatal.
9
+ *
10
+ * Three flags matter and none of them are cosmetic:
11
+ * --ephemeral no rollout is written under ~/.codex/sessions. Without
12
+ * it, each consolidation leaves a session that humemory
13
+ * would later ingest as a trace — memory eating itself.
14
+ * --ignore-user-config skips the user's skills, plugins and hooks. Cheaper
15
+ * (~2k fewer tokens per call, half the latency) and it
16
+ * stops a humemory Stop hook wired into codex from
17
+ * re-entering humemory while maintenance is running.
18
+ * -s read-only consolidation summarises text; it never needs a write.
19
+ */
20
+ import { mkdtempSync, readFileSync, rmSync } from 'fs';
21
+ import { tmpdir } from 'os';
22
+ import { join } from 'path';
23
+ /** Strips the ```json fences a chat-tuned model wraps around structured output. */
24
+ export function unfence(text) {
25
+ const fenced = text.trim().match(/^```(?:json)?\s*\n([\s\S]*?)\n?```$/);
26
+ return (fenced ? fenced[1] : text).trim();
27
+ }
28
+ /** Flattens an Anthropic-shaped request into one prompt string for a CLI turn. */
29
+ export function flattenPrompt(params) {
30
+ const blocks = [];
31
+ const system = params?.system;
32
+ if (typeof system === 'string')
33
+ blocks.push(system);
34
+ else if (Array.isArray(system)) {
35
+ for (const part of system)
36
+ if (typeof part?.text === 'string')
37
+ blocks.push(part.text);
38
+ }
39
+ for (const message of params?.messages ?? []) {
40
+ const content = message?.content;
41
+ if (typeof content === 'string')
42
+ blocks.push(content);
43
+ else if (Array.isArray(content)) {
44
+ for (const part of content)
45
+ if (typeof part?.text === 'string')
46
+ blocks.push(part.text);
47
+ }
48
+ }
49
+ return blocks.join('\n\n');
50
+ }
51
+ export function codexArgs(outputPath, model) {
52
+ return [
53
+ 'exec',
54
+ '--ephemeral',
55
+ '--ignore-user-config',
56
+ '--ignore-rules',
57
+ '--skip-git-repo-check',
58
+ '-s', 'read-only',
59
+ '-c', 'model_reasoning_effort="low"',
60
+ '-c', 'model_verbosity="low"',
61
+ ...(model ? ['-m', model] : []),
62
+ '--color', 'never',
63
+ '-o', outputPath,
64
+ '-',
65
+ ];
66
+ }
67
+ const spawnCodex = async (prompt, { timeoutMs }) => {
68
+ const dir = mkdtempSync(join(tmpdir(), 'humemory-codex-'));
69
+ const outputPath = join(dir, 'last-message.txt');
70
+ try {
71
+ const proc = Bun.spawn(['codex', ...codexArgs(outputPath, process.env.HUMEMORY_LLM_MODEL)], {
72
+ stdin: new TextEncoder().encode(prompt),
73
+ stdout: 'ignore',
74
+ stderr: 'pipe',
75
+ });
76
+ const timer = setTimeout(() => proc.kill(), timeoutMs);
77
+ let code;
78
+ try {
79
+ code = await proc.exited;
80
+ }
81
+ finally {
82
+ clearTimeout(timer);
83
+ }
84
+ if (code !== 0)
85
+ throw new Error(`codex exec exited ${code}: ${(await new Response(proc.stderr).text()).slice(0, 200)}`);
86
+ return readFileSync(outputPath, 'utf-8');
87
+ }
88
+ finally {
89
+ rmSync(dir, { recursive: true, force: true });
90
+ }
91
+ };
92
+ /**
93
+ * Wraps a coding-agent CLI in the `LLMClient` shape the consolidation path expects.
94
+ * Only the fields `generateMemoryLevels` reads are honoured — this is a duck, not
95
+ * an SDK: no streaming, no tools, no token accounting.
96
+ */
97
+ export function createCodexClient(options = {}) {
98
+ const runner = options.runner ?? spawnCodex;
99
+ const timeoutMs = options.timeoutMs ?? 60_000;
100
+ return {
101
+ messages: {
102
+ create: async (params) => {
103
+ const text = await runner(flattenPrompt(params), { timeoutMs });
104
+ return { content: [{ type: 'text', text: unfence(text) }] };
105
+ },
106
+ },
107
+ };
108
+ }
@@ -45,7 +45,15 @@ export declare class SQLiteStore implements MemoryStore, IntentionStore, ScriptS
45
45
  private loadIntoMemory;
46
46
  private rowToMemory;
47
47
  private memoryToRow;
48
- add(memory: Omit<Memory, 'id' | 'createdAt' | 'recallCount' | 'decayRate' | 'currentLevel' | 'saillance'>, options?: {
48
+ /**
49
+ * `createdAt` defaults to now, but a caller encoding an *older* session — a
50
+ * rollout swept days later — passes the instant it was lived. Age is what
51
+ * decay runs on, so a backdated trace arrives already degraded, exactly as if
52
+ * it had been encoded on the day.
53
+ */
54
+ add(memory: Omit<Memory, 'id' | 'createdAt' | 'recallCount' | 'decayRate' | 'currentLevel' | 'saillance'> & {
55
+ createdAt?: Date;
56
+ }, options?: {
49
57
  autoGenerate?: boolean;
50
58
  }): Promise<Memory>;
51
59
  getById(id: string): Promise<Memory | null>;
@@ -493,9 +493,16 @@ export class SQLiteStore {
493
493
  $refuted_count: memory.refutedCount ?? 0,
494
494
  };
495
495
  }
496
+ /**
497
+ * `createdAt` defaults to now, but a caller encoding an *older* session — a
498
+ * rollout swept days later — passes the instant it was lived. Age is what
499
+ * decay runs on, so a backdated trace arrives already degraded, exactly as if
500
+ * it had been encoded on the day.
501
+ */
496
502
  async add(memory, options = {}) {
497
503
  const id = crypto.randomUUID();
498
504
  const now = this.clock.now();
505
+ const createdAt = memory.createdAt ?? now;
499
506
  let generatedLevels = {};
500
507
  if (options.autoGenerate && !memory.level1Summary) {
501
508
  const memType = (memory.memoryType || 'semantic');
@@ -506,11 +513,11 @@ export class SQLiteStore {
506
513
  ...memory,
507
514
  ...generatedLevels,
508
515
  id,
509
- createdAt: now,
516
+ createdAt,
510
517
  recallCount: 0,
511
518
  decayRate: calculateDecayRate(memory.content, memory.keywords),
512
519
  currentLevel: 0,
513
- saillance: calculateSaillance({ ...memory, id, createdAt: now, recallCount: 0, decayRate: 0.5 }, now),
520
+ saillance: calculateSaillance({ ...memory, id, createdAt, recallCount: 0, decayRate: 0.5 }, now),
514
521
  // Phase 6.0.1 — provenance defaults
515
522
  source: memory.source ?? 'agent',
516
523
  verified: memory.verified ?? false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
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",
@@ -5,6 +5,7 @@ import Anthropic from '@anthropic-ai/sdk';
5
5
  import { dirname, join } from 'path';
6
6
  import { fileURLToPath } from 'url';
7
7
  import type { LLMClient } from '../src/core/llm-generator.js';
8
+ import { createCodexClient } from '../src/core/llm-cli-client.js';
8
9
  import { processMaintenanceQueue } from '../src/agent/maintenance-queue.js';
9
10
 
10
11
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -12,16 +13,23 @@ const queueDir = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../data/maintena
12
13
  const dbPath = process.env.HUMEMORY_DB ?? join(__dirname, '../data/humemory.db');
13
14
  const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? 'none';
14
15
 
16
+ const llmTimeoutMs = Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000);
17
+
18
+ // 'none' (the default) keeps consolidation deterministic and network-free.
15
19
  let client: LLMClient | undefined;
16
20
  if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
17
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 });
18
26
  }
19
27
 
20
28
  const result = await processMaintenanceQueue({
21
29
  queueDir,
22
30
  dbPath,
23
31
  client,
24
- llmTimeoutMs: Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000),
32
+ llmTimeoutMs,
25
33
  maxJobs: Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
26
34
  });
27
35