humemory 0.2.4 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +34 -2
- package/dist/agent/claude-hook.js +8 -3
- package/dist/agent/codex-import.d.ts +40 -0
- package/dist/agent/codex-import.js +97 -0
- package/dist/agent/codex-rollout-parser.d.ts +30 -0
- package/dist/agent/codex-rollout-parser.js +111 -0
- package/dist/agent/maintenance-queue.js +2 -2
- package/dist/agent/maintenance-runner.d.ts +90 -0
- package/dist/agent/maintenance-runner.js +188 -0
- package/dist/agent/maintenance-state.d.ts +73 -0
- package/dist/agent/maintenance-state.js +108 -0
- package/dist/agent/session-parser.d.ts +17 -0
- package/dist/agent/session-parser.js +28 -0
- package/dist/api/maintenance-routes.d.ts +25 -0
- package/dist/api/maintenance-routes.js +54 -0
- package/dist/api/server.js +47 -0
- package/dist/cli/index.js +88 -0
- package/dist/core/llm-cli-client.d.ts +43 -0
- package/dist/core/llm-cli-client.js +108 -0
- package/dist/store/sqlite.d.ts +9 -1
- package/dist/store/sqlite.js +9 -2
- package/package.json +3 -1
- package/scripts/maintenance-worker.ts +15 -21
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.2.6] - 2026-08-27
|
|
4
|
+
**Bug Fixes:**
|
|
5
|
+
- stop the 15-min console flash, and make consolidation supervised (#1)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
## [0.2.5] - 2026-08-26
|
|
10
|
+
**Features:**
|
|
11
|
+
- ingest codex sessions, not just claude ones
|
|
12
|
+
- consolidate through the codex CLI, no API key
|
|
13
|
+
|
|
14
|
+
**Bug Fixes:**
|
|
15
|
+
- date a trace on the session's clock, not the sweep's
|
|
16
|
+
|
|
17
|
+
**Documentation:**
|
|
18
|
+
- document codex rollout import
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
3
22
|
## [0.2.4] - 2026-08-23
|
|
4
23
|
**Bug Fixes:**
|
|
5
24
|
- 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 {
|
|
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 =
|
|
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:
|
|
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 {
|
|
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 =
|
|
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
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One maintenance pass: pull in what the local agents wrote since last time,
|
|
3
|
+
* then drain the queue into memory.
|
|
4
|
+
*
|
|
5
|
+
* The pass has exactly one definition here, callable from two places:
|
|
6
|
+
* `scripts/maintenance-worker.ts` (a one-shot CLI run) and the long-lived API
|
|
7
|
+
* process (`startMaintenanceLoop`). It used to live only in the script, driven
|
|
8
|
+
* by a Windows scheduled task whose `cmd` action flashed a console window every
|
|
9
|
+
* 15 minutes; hosting it in the already-resident, windowless API process is what
|
|
10
|
+
* removed the flash.
|
|
11
|
+
*
|
|
12
|
+
* Every pass writes to the state file (src/agent/maintenance-state.ts) whether
|
|
13
|
+
* it succeeds or fails, so a loop that has silently stopped is detectable from
|
|
14
|
+
* the CLI and the API instead of being noticed weeks later.
|
|
15
|
+
*/
|
|
16
|
+
import type { LLMClient } from '../core/llm-generator.js';
|
|
17
|
+
import type { Clock } from '../core/clock.js';
|
|
18
|
+
import { type WorkerResult } from './maintenance-queue.js';
|
|
19
|
+
import { type CodexImportResult } from './codex-import.js';
|
|
20
|
+
export declare const DEFAULT_INTERVAL_MS: number;
|
|
21
|
+
export interface MaintenancePassOptions {
|
|
22
|
+
queueDir?: string;
|
|
23
|
+
dbPath?: string;
|
|
24
|
+
statePath?: string;
|
|
25
|
+
/** Days of codex rollouts to sweep in. `false` skips the codex import entirely. */
|
|
26
|
+
codexSinceDays?: number | false;
|
|
27
|
+
/** Overrides `$CODEX_HOME/sessions`; mainly a test seam. */
|
|
28
|
+
codexSessionsDir?: string;
|
|
29
|
+
client?: LLMClient;
|
|
30
|
+
llmTimeoutMs?: number;
|
|
31
|
+
maxJobs?: number;
|
|
32
|
+
clock?: Clock;
|
|
33
|
+
/** Recorded in the state file so two competing schedulers are visible. */
|
|
34
|
+
runner?: string;
|
|
35
|
+
}
|
|
36
|
+
export interface MaintenancePassResult {
|
|
37
|
+
codex?: CodexImportResult;
|
|
38
|
+
/** Set when the codex import failed; the queue is still drained regardless. */
|
|
39
|
+
codexError?: string;
|
|
40
|
+
worker: WorkerResult;
|
|
41
|
+
}
|
|
42
|
+
export declare function defaultQueueDir(): string;
|
|
43
|
+
export declare function defaultDbPath(): string;
|
|
44
|
+
export declare function defaultLlmTimeoutMs(): number;
|
|
45
|
+
export declare function configuredIntervalMs(): number;
|
|
46
|
+
/**
|
|
47
|
+
* The LLM the pass consolidates with. 'none' (the default) keeps consolidation
|
|
48
|
+
* deterministic and network-free; there is no API key on the production machine
|
|
49
|
+
* and none wanted, so 'codex' shells out to the logged-in CLI instead.
|
|
50
|
+
*/
|
|
51
|
+
export declare function resolveMaintenanceClient(timeoutMs?: number): Promise<LLMClient | undefined>;
|
|
52
|
+
/**
|
|
53
|
+
* Import, then drain, then record. A failing codex import is contained: a
|
|
54
|
+
* missing or unreadable codex must never stall the queue, which holds sessions
|
|
55
|
+
* from every other source.
|
|
56
|
+
*
|
|
57
|
+
* Throws only if the queue itself could not be drained — the caller records
|
|
58
|
+
* that failure and stays alive.
|
|
59
|
+
*/
|
|
60
|
+
export declare function runMaintenancePass(options?: MaintenancePassOptions): Promise<MaintenancePassResult>;
|
|
61
|
+
/** Minimal timer seam, so the loop is testable without waiting on wall time. */
|
|
62
|
+
export interface TimerLike {
|
|
63
|
+
setInterval(handler: () => void, ms: number): unknown;
|
|
64
|
+
clearInterval(handle: unknown): void;
|
|
65
|
+
}
|
|
66
|
+
export interface MaintenanceLoop {
|
|
67
|
+
/** Runs a pass now, outside the schedule. Resolves once it has finished. */
|
|
68
|
+
runNow(): Promise<void>;
|
|
69
|
+
stop(): void;
|
|
70
|
+
/** True while a pass is in flight — the next tick is suppressed until it clears. */
|
|
71
|
+
readonly busy: boolean;
|
|
72
|
+
}
|
|
73
|
+
export interface MaintenanceLoopOptions extends MaintenancePassOptions {
|
|
74
|
+
intervalMs?: number;
|
|
75
|
+
/** Run one pass immediately instead of waiting a full interval. */
|
|
76
|
+
runAtStart?: boolean;
|
|
77
|
+
timers?: TimerLike;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Run a pass every `intervalMs` inside the calling process. The API process is
|
|
81
|
+
* already resident and windowless, so hosting the loop there spawns nothing —
|
|
82
|
+
* which is the whole point of moving it off the Windows scheduler.
|
|
83
|
+
*
|
|
84
|
+
* Three properties this guarantees, each covered by a test:
|
|
85
|
+
* - passes never overlap, on top of the queue's own cross-process lock;
|
|
86
|
+
* - a throwing pass is contained and the loop keeps ticking, because the API
|
|
87
|
+
* must not die of a bad session transcript;
|
|
88
|
+
* - every pass, good or bad, lands in the state file.
|
|
89
|
+
*/
|
|
90
|
+
export declare function startMaintenanceLoop(options?: MaintenanceLoopOptions): MaintenanceLoop;
|