humemory 0.2.3 → 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.
Files changed (38) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/README.md +75 -6
  4. package/dist/agent/claude-hook.js +8 -3
  5. package/dist/agent/codex-import.d.ts +40 -0
  6. package/dist/agent/codex-import.js +97 -0
  7. package/dist/agent/codex-rollout-parser.d.ts +30 -0
  8. package/dist/agent/codex-rollout-parser.js +111 -0
  9. package/dist/agent/maintenance-queue.js +2 -2
  10. package/dist/agent/session-context.js +6 -0
  11. package/dist/agent/session-parser.d.ts +17 -0
  12. package/dist/agent/session-parser.js +28 -0
  13. package/dist/api/cors.d.ts +21 -0
  14. package/dist/api/cors.js +39 -0
  15. package/dist/api/dream-routes.js +2 -1
  16. package/dist/api/errors.d.ts +22 -0
  17. package/dist/api/errors.js +34 -0
  18. package/dist/api/intentions-routes.js +27 -6
  19. package/dist/api/limits.d.ts +58 -0
  20. package/dist/api/limits.js +80 -0
  21. package/dist/api/memory-routes.js +82 -29
  22. package/dist/api/scripts-routes.js +20 -6
  23. package/dist/api/security-headers.d.ts +19 -0
  24. package/dist/api/security-headers.js +47 -0
  25. package/dist/api/server.d.ts +4 -1
  26. package/dist/api/server.js +20 -10
  27. package/dist/cli/index.js +36 -0
  28. package/dist/core/cues.d.ts +16 -0
  29. package/dist/core/cues.js +56 -3
  30. package/dist/core/llm-cli-client.d.ts +43 -0
  31. package/dist/core/llm-cli-client.js +108 -0
  32. package/dist/store/sqlite.d.ts +9 -1
  33. package/dist/store/sqlite.js +9 -2
  34. package/package.json +2 -1
  35. package/public/app/index-95ffty7j.js +12 -0
  36. package/public/app/index.html +1 -1
  37. package/scripts/maintenance-worker.ts +9 -1
  38. package/public/app/index-nqr7bd0a.js +0 -12
package/AGENTS.md CHANGED
@@ -322,7 +322,7 @@ accepts a script id as the loser. API: `POST/GET /scripts`,
322
322
  `tests/helpers/fixtures.ts` shipped with S5-00b. New Phase 6/7/8 suites still lean on inline
323
323
  literals for scenario-specific content (fine per [docs/TESTING.md](./docs/TESTING.md)'s own
324
324
  rule — a fixture is for shared corpora, not a one-off case a test is *about*).
325
- - `vitest.config.ts` orphaned; suite runs under `bun test` (BUG-06).
325
+ - ~~`vitest.config.ts` orphaned~~ — closed: the file is gone, the suite runs under `bun test`.
326
326
  - `tsc` global can shadow local — `pnpm build` is `tsc -p tsconfig.json`.
327
327
 
328
328
  ## 📝 Notes
package/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
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
+
16
+ ## [0.2.4] - 2026-08-23
17
+ **Bug Fixes:**
18
+ - stop returning internal error detail to clients (L-01)
19
+ - exact-match CORS origins and add browser defence headers (M-04)
20
+ - bound request bodies, collections and cost parameters (M-02)
21
+ - bound error_pattern regex evaluation (M-01)
22
+
23
+ **Documentation:**
24
+ - document the API security config and correct stale status claims
25
+ - record the remediation status in the security audit
26
+
27
+ **Tests:**
28
+ - cover the full audit attack chain end to end
29
+
30
+ **CI/CD:**
31
+ - pin the release chain and drop unused permission (M-03)
32
+
33
+
34
+
3
35
  ## [0.2.3] - 2026-08-17
4
36
  **Features:**
5
37
  - add Streamable HTTP transport and security hardening
package/README.md CHANGED
@@ -16,7 +16,8 @@ not when you run a full-text search for "milk".
16
16
 
17
17
  ## Two halves of a brain
18
18
 
19
- humemory is built in two halves. The first is shipped. The second is its destiny.
19
+ humemory is built in two halves. The first was shipped first; the second is what it
20
+ was always for. Both are built as of Phase 8.
20
21
 
21
22
  ### 1. Retrospective memory — *what was learned* ✅ built
22
23
 
@@ -40,7 +41,7 @@ construction.
40
41
  A Claude Code `Stop` hook can queue each completed session instantly; maintenance
41
42
  extracts and stores its learnings afterward, outside the agent's critical path.
42
43
 
43
- ### 2. Prospective memory — *what to resurface* 🎯 the destiny
44
+ ### 2. Prospective memory — *what to resurface* ✅ built
44
45
 
45
46
  The second half (see `AGENTS.md` → Phase 5) is what gives humemory its life:
46
47
 
@@ -95,6 +96,28 @@ An entry means **ready to be discovered**, not that its evolving private session
95
96
  format is already parsed. Run `pnpm cli sources discover --installed-only` for a
96
97
  local inventory without exposing conversation content.
97
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
+
98
121
  The React app is served at **`/`** (and `/app`). The original vanilla dashboard
99
122
  has been removed — the React front reached parity first, and git keeps the old
100
123
  one if it is ever needed.
@@ -197,6 +220,15 @@ Claude as an asynchronous quality enhancement, set
197
220
  timeouts fall back to the deterministic extractor. A queue item is deleted only
198
221
  after its extracted memories are committed successfully.
199
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
+
200
232
  The queue directory is the whole contract, and it is inspectable at any time:
201
233
 
202
234
  | Entry | Meaning |
@@ -211,8 +243,9 @@ The queue directory is the whole contract, and it is inspectable at any time:
211
243
  | --- | --- | --- |
212
244
  | `HUMEMORY_DB` | `data/humemory.db` | database path |
213
245
  | `HUMEMORY_QUEUE` | `data/maintenance-queue` | durable raw-session inbox |
214
- | `HUMEMORY_MAINTENANCE_LLM` | `none` | optional enhancement (`anthropic`) |
215
- | `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 |
216
249
  | `HUMEMORY_DIR` | `cwd` | mental place to scope loops and traces to |
217
250
  | `HUMEMORY_SESSION_BUDGET` | `10` | max items listed per section |
218
251
  | `HUMEMORY_SAILLANCE_MIN` | `60` | salience floor for recalling a decayed trace |
@@ -220,6 +253,41 @@ The queue directory is the whole contract, and it is inspectable at any time:
220
253
 
221
254
  ---
222
255
 
256
+ ## Serving the API safely
257
+
258
+ The database holds every learning trace and open loop across all your projects,
259
+ and the API can read, alter and delete all of it. Treat the port as sensitive.
260
+
261
+ | Env var | Default | Effect |
262
+ | --- | --- | --- |
263
+ | `PORT` | `3456` | API/dashboard port |
264
+ | `HUMEMORY_HOST` | `127.0.0.1` | listen address — **loopback only unless you change it** |
265
+ | `HUMEMORY_API_TOKEN` | unset | when set, required on every data route (`Authorization: Bearer …` or `X-Humemory-Token`) |
266
+ | `CORS_ORIGINS` | `http://localhost:3456` | comma-separated exact origins, honoured when `NODE_ENV=production` |
267
+ | `HUMEMORY_VERBOSE_ERRORS` | unset | `1` returns real error messages instead of a correlation id — local debugging only |
268
+
269
+ **Defaults are private.** The server binds `127.0.0.1`, so nothing on your network
270
+ can reach it. Without `HUMEMORY_API_TOKEN` it starts anyway and warns, because on
271
+ loopback the OS is the boundary.
272
+
273
+ **Exposing it is deliberate.** Setting `HUMEMORY_HOST` to anything but loopback
274
+ *without* a token makes the server refuse to start rather than quietly publish your
275
+ memory to the LAN:
276
+
277
+ ```bash
278
+ HUMEMORY_HOST=0.0.0.0 HUMEMORY_API_TOKEN="$(openssl rand -hex 32)" pnpm start:api
279
+ ```
280
+
281
+ The dashboard asks for that token behind the 🔑 button in its header and keeps it
282
+ in `localStorage`. `/health` and the static assets stay open so a probe and the
283
+ page itself still load.
284
+
285
+ A token is not a substitute for the network layer: over anything but loopback, put
286
+ TLS and a firewall in front of it. The token travels in a header, in clear, over
287
+ plain HTTP.
288
+
289
+ ---
290
+
223
291
  ## Why it exists
224
292
 
225
293
  A log remembers everything and reminds you of nothing. A human memory forgets most
@@ -564,8 +632,9 @@ keywords >5. `photographic: true` disables decay entirely.
564
632
 
565
633
  ## Known issues
566
634
  - ~~SQLite multi-process: advisory lock~~ — fixed in Sprint 5 (S5-00a): WAL + write-queue (Sprint 4) plus file-based cross-process `AdvisoryLock`.
567
- - `tests/fixtures/` missing — suites seed ad hoc literals (BUG-05, due with S5-00b).
568
- - `vitest.config.ts` orphaned; suite runs under `bun test` (BUG-06).
635
+ - ~~`tests/fixtures/` missing~~ — closed (S5-00b): `tests/fixtures/*.json` + `tests/helpers/fixtures.ts`.
636
+ Shared corpora live there; a one-off case a test is specifically *about* stays inline.
637
+ - ~~`vitest.config.ts` orphaned~~ — closed: the file is gone, the suite runs under `bun test`.
569
638
  - `tsc` global can shadow local — `pnpm build` is `tsc -p tsconfig.json`.
570
639
 
571
640
  ## Notes
@@ -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
@@ -186,6 +186,10 @@ function renderMarkdown(input) {
186
186
  lines.push('', '### ⏰ Deadlines reached', RECALLED_NOTES_PREFACE);
187
187
  for (const i of firedNow) {
188
188
  const s = sanitizeTrace(i.content);
189
+ // Same reporting as scripts and traces: the content was already
190
+ // neutralised, but a swallowed count hides the attempt from the operator.
191
+ if (s.escapedMarkers > 0)
192
+ escapeAttempts.push({ memoryId: i.id, count: s.escapedMarkers });
189
193
  lines.push(`- **[${loopId(i.id)}]** ${renderIntentionBody(i, s)}`);
190
194
  }
191
195
  }
@@ -197,6 +201,8 @@ function renderMarkdown(input) {
197
201
  ? ` — due in ${humanizeAge(now, i.expiresAt).replace(' ago', '')}`
198
202
  : '';
199
203
  const s = sanitizeTrace(i.content);
204
+ if (s.escapedMarkers > 0)
205
+ escapeAttempts.push({ memoryId: i.id, count: s.escapedMarkers });
200
206
  lines.push(`- **[${loopId(i.id)}]** ${renderIntentionBody(i, s)} (armed ${age}${deadline})`);
201
207
  }
202
208
  lines.push('', `_To close a loop: mention \`Closes ${loopId(openLoops[0].id)}\` in a commit message._`);
@@ -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
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * CORS origin allow-list (SECURITY_AUDIT.md M-04).
3
+ *
4
+ * Extracted from `server.ts` for the same reason as the route modules: importing
5
+ * `server.ts` constructs the store and would open the production database, so
6
+ * anything that needs testing lives outside it (BUG-08).
7
+ */
8
+ /**
9
+ * Normalises an origin to its canonical `scheme://host[:port]` form, or null if
10
+ * it is not a parseable absolute URL.
11
+ */
12
+ export declare function normalizeOrigin(value: string): string | null;
13
+ /**
14
+ * Builds an exact-match origin checker for hono's `cors({ origin })`.
15
+ *
16
+ * The previous check was `origin.includes(allowed)`, a substring test: with a
17
+ * custom CORS_ORIGINS entry, `http://localhost:3456.evil.example` contains the
18
+ * allowed value and passed. Both sides are now parsed and compared as whole
19
+ * origins, and anything unparseable is refused.
20
+ */
21
+ export declare function makeOriginChecker(allowed: string[]): (origin: string) => string | undefined;