opencode-codex-memory 0.1.2

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Moritz Flöter
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ opencode-codex-memory
2
+ Copyright 2026 Moritz Flöter
3
+
4
+ This project is a TypeScript port of the memory system from
5
+ OpenAI Codex (https://github.com/openai/codex), licensed under the
6
+ Apache License 2.0. Copyright 2025 OpenAI.
7
+
8
+ The prompt templates under src/templates/ are adapted from Codex's
9
+ memory templates. Per-file provenance is tracked in codex-map.yaml.
package/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # opencode-codex-memory
2
+
3
+ Persistent memory for [opencode](https://opencode.ai). Your agent remembers what
4
+ it learned in past sessions — your conventions, your projects, the decisions you
5
+ made — and brings that context into new conversations automatically.
6
+
7
+ It's a single plugin. No core changes, no MCP server, no separate process, no
8
+ cloud service. Everything stays on your machine under
9
+ `~/.local/share/opencode/`.
10
+
11
+ ## Why
12
+
13
+ By default every opencode session starts from zero. You re-explain your build
14
+ commands, your code style, and the quirks of each repo over and over.
15
+
16
+ opencode-codex-memory closes that loop:
17
+
18
+ - **It learns in the background.** After a session goes idle, the plugin reviews
19
+ the transcript and extracts durable facts — preferences, project structure,
20
+ what worked and what didn't.
21
+ - **It consolidates.** Periodically it merges those notes into a compact,
22
+ searchable memory, pruning what's stale.
23
+ - **It remembers at the right time.** A short summary is injected into the system
24
+ prompt, and the agent can search the full memory on demand when a task looks
25
+ related to past work.
26
+ - **It self-corrects.** When the agent actually uses a memory it cites the source,
27
+ so useful memories rank higher over time and unused ones fade.
28
+
29
+ The result: opencode gets more useful the more you use it, without you managing
30
+ anything.
31
+
32
+ ## Install
33
+
34
+ 1. Add the plugin to your `~/.config/opencode/opencode.json`:
35
+
36
+ ```json
37
+ {
38
+ "plugin": ["opencode-codex-memory"]
39
+ }
40
+ ```
41
+
42
+ (While developing locally, point it at an absolute path to your checkout
43
+ instead of the package name.)
44
+
45
+ 2. That's it. The memory workspace is created on first use. Installing the
46
+ plugin is the opt-in: background learning and summary injection are active
47
+ immediately (codex ships the same system behind an experimental flag with a
48
+ consent prompt; a standalone memory plugin *is* the consent).
49
+
50
+ Requires only opencode (official release). Git is bundled (`isomorphic-git`) —
51
+ no `git` binary or any other external tool needed.
52
+
53
+ The two restricted sub-agents that do the background learning (`memorize`,
54
+ `memorize-extract`) register themselves automatically. To customize one — e.g.
55
+ pin a cheaper model for extraction — define an agent with the same name in your
56
+ own config; your definition wins and the plugin leaves it alone.
57
+
58
+ ## Try it
59
+
60
+ Just use opencode normally. After a session goes idle, the plugin reviews it in
61
+ the background and starts building memory — you don't have to do anything. Come
62
+ back for a later session and ask something like *"what do you know about how I
63
+ work?"* or *"what was I doing in this repo?"* and the agent draws on what it
64
+ learned. The more you use it, the more it knows.
65
+
66
+ You can also steer it in plain language, mid-conversation:
67
+
68
+ - *"remember that I deploy this project with `make release`"* → saved as a note.
69
+ - *"what was I working on in this repo last week?"* → time-scoped recall.
70
+ - *"reset my memory"* → wipes it and starts over.
71
+
72
+ Want to prime it before the first session has a chance to be learned? You can
73
+ drop a starter summary in yourself — it's just a file:
74
+
75
+ ```bash
76
+ mkdir -p ~/.local/share/opencode/memories
77
+ echo 'I prefer TypeScript strict mode and 2-space indentation.' \
78
+ > ~/.local/share/opencode/memories/memory_summary.md
79
+ ```
80
+
81
+ ## Where your data lives
82
+
83
+ ```
84
+ ~/.local/share/opencode/
85
+ ├── memory.db # the plugin's own database (never touches opencode's)
86
+ └── memories/
87
+ ├── memory_summary.md # compact summary injected into the system prompt
88
+ ├── MEMORY.md # searchable index of everything learned
89
+ ├── rollout_summaries/ # one recap per past session
90
+ ├── skills/ # reusable procedures discovered over time
91
+ └── extensions/ad_hoc/notes/ # things you explicitly asked it to remember
92
+ ```
93
+
94
+ It's all plain files and a local SQLite database. Read them, edit them, delete
95
+ them, or check them into a private repo — it's yours.
96
+
97
+ ## Privacy & safety
98
+
99
+ - **Local only.** Nothing is sent anywhere except through your existing opencode
100
+ provider, using your existing credentials. The plugin holds no keys of its own.
101
+ - **Secrets are redacted** (API keys, tokens, private keys, passwords) before any
102
+ memory is written or sent to a model.
103
+ - **The learning agents are sandboxed** — they cannot run shell commands or reach
104
+ the network.
105
+ - **Reset is safe.** `memory_reset` refuses to run if the memory folder is a
106
+ symlink, so it can't be tricked into deleting something else.
107
+ - **Web/MCP sessions:** by default, sessions that used web search, fetch, or MCP
108
+ tools are still eligible for memory (matching codex). If you'd rather exclude
109
+ them so scraped or external content can't enter your memory, set
110
+ `disable_on_external_context: true`.
111
+
112
+ ## Configuration
113
+
114
+ Optional plugin options (all have sensible defaults). Names and defaults match
115
+ codex's `[memories]` config so the two stay easy to compare:
116
+
117
+ | Option | Default | Meaning |
118
+ |---|---|---|
119
+ | `generate_memories` | `true` | Turn the background learning pipeline on/off |
120
+ | `use_memories` | `true` | Inject the memory summary into the system prompt |
121
+ | `dedicated_tools` | `true` | Expose the `memory_read`/`memory_search`/`memory_list`/`memory_add_note` tools |
122
+ | `disable_on_external_context` | `false` | Exclude sessions that used web/MCP tools from memory |
123
+ | `extract_model` | opencode `small_model`, else current model | Model used for per-session extraction |
124
+ | `consolidation_model` | opencode `model`, else current model | Model used for consolidation |
125
+ | `max_raw_memories_for_consolidation` | `256` | How many raw memories feed each consolidation pass |
126
+ | `max_rollout_age_days` | `10` | Ignore sessions older than this for extraction |
127
+ | `min_rollout_idle_hours` | `6` | How long a session must be idle before it's eligible |
128
+ | `max_rollouts_per_startup` | `2` | Max sessions extracted per pass |
129
+ | `max_unused_days` | `30` | Prune memories unused for this long |
130
+
131
+ To set options, turn the plugin entry into a `[name, options]` pair:
132
+
133
+ ```json
134
+ {
135
+ "plugin": [
136
+ ["opencode-codex-memory", { "disable_on_external_context": true, "min_rollout_idle_hours": 2 }]
137
+ ]
138
+ }
139
+ ```
140
+
141
+ See the [opencode plugin docs](https://opencode.ai/docs/plugins/) for details.
142
+
143
+ Numeric options are clamped to codex's valid ranges; unknown option keys are
144
+ ignored with a warning. Setting `use_memories: false` also hides the memory
145
+ tools, matching codex's extension gating.
146
+
147
+ Model selection mirrors codex's cheap-extraction / capable-consolidation
148
+ split using opencode's own concepts: when `extract_model` is unset, the
149
+ `small_model` from your `opencode.json` is used (codex uses `gpt-5.4-mini`);
150
+ when `consolidation_model` is unset, your main `model` is used (codex uses
151
+ `gpt-5.4`). If neither is configured, both fall back to the session's default
152
+ model. (opencode's *automatic* small-model pick is internal to opencode and
153
+ not exposed to plugins — set `small_model` explicitly to get the cheap
154
+ extraction path.)
155
+
156
+ > Note: `dedicated_tools` defaults to `true` here (codex defaults it to `false`).
157
+ > This is the one intentional default difference — the tools are a core part of a
158
+ > standalone memory plugin. Everything else matches codex's defaults.
159
+
160
+ ## Under the hood
161
+
162
+ opencode-codex-memory is a faithful port of the memory system from OpenAI's codex.
163
+ If you want to understand the design, the trade-offs, or contribute, see
164
+ [`ARCHITECTURE.md`](./ARCHITECTURE.md). Contributor guidance lives in
165
+ [`CONTRIBUTING.md`](./CONTRIBUTING.md) and [`AGENTS.md`](./AGENTS.md) —
166
+ in short: this repo exists to port codex's memory system to opencode, and
167
+ PRs that break that parity will be rejected.
168
+
169
+ ## License
170
+
171
+ Apache 2.0 — the same license as [OpenAI Codex](https://github.com/openai/codex),
172
+ whose memory system this project ports. See [`LICENSE`](./LICENSE) and
173
+ [`NOTICE`](./NOTICE). Not affiliated with the codex project.
package/opencode.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "$schema": "https://opencode.ai/config.json",
3
+ "agent": {
4
+ "memorize": {
5
+ "mode": "subagent",
6
+ "prompt": "You are a memory consolidation agent. Read the workspace diff file and update MEMORY.md, memory_summary.md, and skills/ to reflect the latest memories. Keep memory_summary.md under 10000 chars (2500 tokens). Prune stale entries. Do not access the network.",
7
+ "permission": {
8
+ "bash": "deny",
9
+ "webfetch": "deny",
10
+ "websearch": "deny",
11
+ "task": "deny",
12
+ "todowrite": "deny",
13
+ "read": "allow",
14
+ "edit": "allow",
15
+ "write": "allow",
16
+ "glob": "allow",
17
+ "grep": "allow"
18
+ }
19
+ },
20
+ "memorize-extract": {
21
+ "mode": "subagent",
22
+ "prompt": "You are a memory extraction agent. Read the session transcript and extract raw_memory, rollout_summary, and rollout_slug as JSON. Exclude AGENTS.md/instruction content. Redact secrets.",
23
+ "permission": {
24
+ "bash": "deny",
25
+ "webfetch": "deny",
26
+ "websearch": "deny",
27
+ "task": "deny",
28
+ "todowrite": "deny",
29
+ "read": "allow",
30
+ "write": "deny",
31
+ "edit": "deny",
32
+ "glob": "allow",
33
+ "grep": "allow"
34
+ }
35
+ }
36
+ }
37
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "opencode-codex-memory",
3
+ "version": "0.1.2",
4
+ "description": "Persistent memory plugin for opencode — ports codex's two-phase memory system (extraction → consolidation → injection → citation feedback)",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "files": [
8
+ "src",
9
+ "tools",
10
+ "opencode.json",
11
+ "NOTICE"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/moritzfl/opencode-codex-memory.git"
16
+ },
17
+ "homepage": "https://github.com/moritzfl/opencode-codex-memory#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/moritzfl/opencode-codex-memory/issues"
20
+ },
21
+ "scripts": {
22
+ "dev": "bun --watch src/index.ts",
23
+ "build": "bun build src/index.ts --outdir dist --target bun",
24
+ "test": "bun test",
25
+ "typecheck": "tsc --noEmit"
26
+ },
27
+ "keywords": ["opencode", "memory", "plugin", "ai", "persistent-context", "codex"],
28
+ "license": "Apache-2.0",
29
+ "dependencies": {
30
+ "@opencode-ai/plugin": "^1.17.13",
31
+ "diff": "^9.0.0",
32
+ "isomorphic-git": "^1.38.6"
33
+ },
34
+ "devDependencies": {
35
+ "typescript": "^5.5.0",
36
+ "@types/bun": "^1.1.0"
37
+ },
38
+ "engines": {
39
+ "bun": ">=1.1.0"
40
+ }
41
+ }
package/src/capture.ts ADDED
@@ -0,0 +1,137 @@
1
+ import { Database } from "bun:sqlite"
2
+ import { opencodeDbPath } from "./paths.js"
3
+ import { MemoryStore, SCAN_LIMIT } from "./store.js"
4
+
5
+ export interface SessionRow {
6
+ id: string
7
+ updated_at: number
8
+ directory: string | null
9
+ }
10
+
11
+ let opencodeDb: Database | null = null
12
+
13
+ function openOpencodeDb(): Database | null {
14
+ if (opencodeDb) return opencodeDb
15
+ const p = opencodeDbPath()
16
+ try {
17
+ opencodeDb = new Database(p, { readonly: true })
18
+ } catch {
19
+ opencodeDb = null
20
+ }
21
+ return opencodeDb
22
+ }
23
+
24
+ export function listRecentSessions(limit: number = SCAN_LIMIT): SessionRow[] {
25
+ const db = openOpencodeDb()
26
+ if (!db) return []
27
+ try {
28
+ // Top-level sessions only: task-tool children are summarized into their
29
+ // parent, and the plugin's own sub-sessions must never be memorized.
30
+ return db
31
+ .prepare(
32
+ `SELECT id, time_updated AS updated_at, directory FROM session
33
+ WHERE parent_id IS NULL AND title NOT LIKE 'codex-memory-%'
34
+ ORDER BY time_updated DESC LIMIT ?`,
35
+ )
36
+ .all(limit) as SessionRow[]
37
+ } catch {
38
+ return []
39
+ }
40
+ }
41
+
42
+ export interface TranscriptMessage {
43
+ type: string
44
+ role?: string
45
+ text?: string
46
+ seq: number
47
+ }
48
+
49
+ export function loadTranscript(sessionId: string): TranscriptMessage[] {
50
+ const db = openOpencodeDb()
51
+ if (!db) return []
52
+ try {
53
+ const rows = db
54
+ .prepare(
55
+ `SELECT p.data, m.data AS msg_data
56
+ FROM part p
57
+ JOIN message m ON p.message_id = m.id
58
+ WHERE p.session_id = ?
59
+ ORDER BY p.time_created ASC`,
60
+ )
61
+ .all(sessionId) as { data: string; msg_data: string }[]
62
+ return rows.map((r, i) => {
63
+ let parsed: any = {}
64
+ try {
65
+ parsed = JSON.parse(r.data)
66
+ } catch {
67
+ }
68
+ let role: string | undefined
69
+ try {
70
+ const msg = JSON.parse(r.msg_data)
71
+ role = msg.role
72
+ } catch {
73
+ }
74
+ return {
75
+ seq: i,
76
+ type: parsed.type ?? "unknown",
77
+ role,
78
+ text: extractText(parsed),
79
+ }
80
+ })
81
+ } catch {
82
+ return []
83
+ }
84
+ }
85
+
86
+ function extractText(msg: any): string | undefined {
87
+ if (!msg) return undefined
88
+ if (typeof msg.text === "string") return msg.text
89
+ if (msg.type === "tool") {
90
+ // Full tool payloads: codex serializes complete FunctionCall/Output items
91
+ // and relies solely on the global transcript truncation. Tool outputs are
92
+ // the extractor's strongest evidence — do not slice them per call.
93
+ const tool = msg.tool ?? "unknown"
94
+ const input = msg.state?.input ? JSON.stringify(msg.state.input) : ""
95
+ const output = typeof msg.state?.output === "string" ? msg.state.output : ""
96
+ return `[tool: ${tool}] ${input}${output ? "\n" + output : ""}`
97
+ }
98
+ if (msg.type === "step-start" || msg.type === "step-finish") return undefined
99
+ if (Array.isArray(msg.parts)) {
100
+ return msg.parts
101
+ .filter((p: any) => p?.type === "text" && typeof p.text === "string")
102
+ .map((p: any) => p.text)
103
+ .join("\n")
104
+ }
105
+ if (Array.isArray(msg.content)) {
106
+ return msg.content
107
+ .filter((c: any) => typeof c === "string" || typeof c?.text === "string")
108
+ .map((c: any) => (typeof c === "string" ? c : c.text))
109
+ .join("\n")
110
+ }
111
+ return undefined
112
+ }
113
+
114
+ export interface EligibilityOptions {
115
+ maxAgeDays: number
116
+ minIdleHours: number
117
+ excludeSession?: string
118
+ }
119
+
120
+ export function selectEligibleSessions(
121
+ store: MemoryStore,
122
+ opts: EligibilityOptions,
123
+ ): SessionRow[] {
124
+ const now = Date.now()
125
+ const minUpdated = now - opts.maxAgeDays * 24 * 60 * 60 * 1000
126
+ const maxUpdated = now - opts.minIdleHours * 60 * 60 * 1000
127
+ const sessions = listRecentSessions()
128
+ return sessions.filter((s) => {
129
+ if (opts.excludeSession && s.id === opts.excludeSession) return false
130
+ if (s.updated_at < minUpdated) return false
131
+ if (s.updated_at > maxUpdated) return false
132
+ const mode = store.getMemoryMode(s.id)
133
+ if (mode === "disabled") return false
134
+ if (store.isPolluted(s.id)) return false
135
+ return true
136
+ })
137
+ }