@zilliz/memsearch-opencode 0.3.0 → 0.3.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/README.md +11 -2
- package/index.ts +16 -1
- package/package.json +1 -1
- package/prompts/project_review.txt +42 -0
- package/prompts/user_profile.txt +42 -0
- package/scripts/capture-daemon.py +69 -2
- package/scripts/maintenance-runner.py +260 -0
- package/scripts/opencode_turns.py +3 -3
- package/skills/memory-config/SKILL.md +157 -0
package/README.md
CHANGED
|
@@ -148,13 +148,22 @@ memsearch config set embedding.provider openai
|
|
|
148
148
|
export OPENAI_API_KEY=sk-...
|
|
149
149
|
```
|
|
150
150
|
|
|
151
|
-
To override only the OpenCode capture summarization model:
|
|
151
|
+
To override only the OpenCode native capture summarization model:
|
|
152
152
|
|
|
153
153
|
```bash
|
|
154
154
|
memsearch config set plugins.opencode.summarize.model anthropic/claude-haiku
|
|
155
155
|
```
|
|
156
156
|
|
|
157
|
-
|
|
157
|
+
To use a memsearch-managed API provider instead:
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
memsearch config set llm.providers.openai.type openai
|
|
161
|
+
memsearch config set llm.providers.openai.model gpt-5-mini
|
|
162
|
+
memsearch config set llm.providers.openai.api_key env:OPENAI_API_KEY
|
|
163
|
+
memsearch config set plugins.opencode.summarize.provider openai
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Leave `plugins.opencode.summarize.provider` empty or set it to `native` to keep the current `small_model` / plugin default behavior. This setting does not fall back to `llm.model`.
|
|
158
167
|
|
|
159
168
|
## How It Works
|
|
160
169
|
|
package/index.ts
CHANGED
|
@@ -19,11 +19,12 @@ import {
|
|
|
19
19
|
existsSync,
|
|
20
20
|
mkdirSync,
|
|
21
21
|
readdirSync,
|
|
22
|
+
realpathSync,
|
|
22
23
|
} from "node:fs";
|
|
23
24
|
import { join, dirname } from "node:path";
|
|
24
25
|
import { fileURLToPath } from "node:url";
|
|
25
26
|
|
|
26
|
-
const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url));
|
|
27
|
+
const PLUGIN_DIR = dirname(realpathSync(fileURLToPath(import.meta.url)));
|
|
27
28
|
|
|
28
29
|
// ---------------------------------------------------------------------------
|
|
29
30
|
// Helpers
|
|
@@ -167,6 +168,19 @@ function stopCaptureDaemon(projectDir: string): void {
|
|
|
167
168
|
}
|
|
168
169
|
}
|
|
169
170
|
|
|
171
|
+
function wakeMaintenance(projectDir: string, memsearchDir: string): void {
|
|
172
|
+
const runner = join(PLUGIN_DIR, "scripts", "maintenance-runner.py");
|
|
173
|
+
exec(
|
|
174
|
+
`python3 '${shellEscape(runner)}' --platform opencode ` +
|
|
175
|
+
`--project-dir '${shellEscape(projectDir)}' --memsearch-dir '${shellEscape(memsearchDir)}' &`,
|
|
176
|
+
{
|
|
177
|
+
timeout: 5000,
|
|
178
|
+
env: { ...process.env, MEMSEARCH_NO_WATCH: "1" },
|
|
179
|
+
},
|
|
180
|
+
() => { /* ignore */ }
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
170
184
|
// ---------------------------------------------------------------------------
|
|
171
185
|
// Plugin entry
|
|
172
186
|
// ---------------------------------------------------------------------------
|
|
@@ -212,6 +226,7 @@ const MemsearchPlugin: Plugin = async ({ project, directory, worktree }) => {
|
|
|
212
226
|
// Start capture daemon for auto-capture
|
|
213
227
|
if (autoCapture) {
|
|
214
228
|
startCaptureDaemon(projectDir, collectionName, memsearchCmd);
|
|
229
|
+
wakeMaintenance(projectDir, memsearchDir);
|
|
215
230
|
}
|
|
216
231
|
|
|
217
232
|
return {
|
package/package.json
CHANGED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
You are maintaining a durable project memory file for {{AGENT_NAME}}.
|
|
2
|
+
|
|
3
|
+
Task: {{TASK_NAME}}
|
|
4
|
+
Project directory: {{PROJECT_DIR}}
|
|
5
|
+
Input memory directory: {{INPUT_DIR}}
|
|
6
|
+
Output file: {{OUTPUT_FILE}}
|
|
7
|
+
|
|
8
|
+
You will receive the current output file and recent memory journal entries. Update the output only when there is durable project information worth preserving.
|
|
9
|
+
|
|
10
|
+
Rules:
|
|
11
|
+
- Return only a JSON object, with no prose outside JSON.
|
|
12
|
+
- Use action "none" when the recent journals do not add durable project state.
|
|
13
|
+
- Use action "replace" when recent journals contain a durable project decision, risk, constraint, active thread, or next step that is not already represented in the existing output file.
|
|
14
|
+
- Treat journal lines explicitly labeled as project decision, project progress, project risk, project constraint, active thread, open question, or next step as project state unless they are clearly temporary noise.
|
|
15
|
+
- Recent progress should be recorded when it changes implementation status, validation status, release status, or an important debugging/testing behavior.
|
|
16
|
+
- If the existing output file is empty and recent journals contain any durable project state, use action "replace".
|
|
17
|
+
- Use action "replace" only when the output file should be replaced.
|
|
18
|
+
- The "content" field, when present, must be the full replacement Markdown file.
|
|
19
|
+
- Preserve useful existing content. Do not rewrite for style.
|
|
20
|
+
- Do not copy raw journals or raw transcript excerpts wholesale.
|
|
21
|
+
- Keep this file about the project, not the user. Put stable user preferences, communication style, and personal workflow notes in USER.md instead.
|
|
22
|
+
- Include user constraints only when they directly affect this project's execution.
|
|
23
|
+
- Do not include general user preferences such as preferred language, dependency manager, PR wording style, verification style, or communication style unless the project has explicitly decided to encode them as project requirements.
|
|
24
|
+
- Suggested sections are optional. Include only sections that are useful.
|
|
25
|
+
- Keep the file concise and reviewable.
|
|
26
|
+
- Prefer small targeted additions over broad rewrites when the existing output is already useful.
|
|
27
|
+
|
|
28
|
+
Suggested Markdown shape:
|
|
29
|
+
- # Project Memory
|
|
30
|
+
- ## Current Direction
|
|
31
|
+
- ## Active Threads
|
|
32
|
+
- ## Recent Progress
|
|
33
|
+
- ## Decisions
|
|
34
|
+
- ## Open Questions
|
|
35
|
+
- ## Risks and Constraints
|
|
36
|
+
- ## Next Steps
|
|
37
|
+
- ## Cold Items
|
|
38
|
+
|
|
39
|
+
JSON examples:
|
|
40
|
+
{"action":"none","reason":"Recent journals do not change durable project state."}
|
|
41
|
+
|
|
42
|
+
{"action":"replace","reason":"Recent journals add a new active thread.","content":"# Project Memory\n\n## Current Direction\n..."}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
You are maintaining a conservative user/workflow profile for {{AGENT_NAME}}.
|
|
2
|
+
|
|
3
|
+
Task: {{TASK_NAME}}
|
|
4
|
+
Project directory: {{PROJECT_DIR}}
|
|
5
|
+
Input memory directory: {{INPUT_DIR}}
|
|
6
|
+
Output file: {{OUTPUT_FILE}}
|
|
7
|
+
|
|
8
|
+
You will receive the current output file and recent memory journal entries. Update the output only when there is stable evidence about the user's durable preferences, priorities, constraints, or repeated workflows.
|
|
9
|
+
|
|
10
|
+
Rules:
|
|
11
|
+
- Return only a JSON object, with no prose outside JSON.
|
|
12
|
+
- Use action "none" when the recent journals do not add stable user/workflow information.
|
|
13
|
+
- Use action "replace" when recent journals contain a stable user preference, priority, constraint, communication style, or repeated workflow that is not already represented in the existing output file.
|
|
14
|
+
- If the existing output file is empty and recent journals contain stable user/workflow information, use action "replace".
|
|
15
|
+
- Use action "replace" only when the output file should be replaced.
|
|
16
|
+
- The "content" field, when present, must be the full replacement Markdown file.
|
|
17
|
+
- Preserve useful existing content. Do not rewrite for style.
|
|
18
|
+
- Do not infer broad personality traits from one-off messages.
|
|
19
|
+
- Keep this file about the user and reusable workflow patterns, not transient project status. Put active project threads and implementation state in PROJECT.md instead.
|
|
20
|
+
- Do not include project technical constraints, implementation decisions, file paths, bug fixes, or architecture decisions unless they are evidence of a repeated user preference across projects.
|
|
21
|
+
- Lines labeled as project decision, project progress, project risk, implementation note, or project constraint belong in PROJECT.md, not USER.md.
|
|
22
|
+
- Do not rewrite project decisions as "User prefers ...". Only include a preference when the journal explicitly describes a user preference, communication preference, workflow preference, or repeated behavior.
|
|
23
|
+
- Treat raw transcript excerpts, when provided, as stronger evidence for wording, style, and decision context.
|
|
24
|
+
- Do not copy raw journals or raw transcript excerpts wholesale.
|
|
25
|
+
- Suggested sections are optional. Include only sections that are useful.
|
|
26
|
+
- Keep the file concise and reviewable.
|
|
27
|
+
- Prefer small targeted additions over broad rewrites when the existing output is already useful.
|
|
28
|
+
|
|
29
|
+
Suggested Markdown shape:
|
|
30
|
+
- # User Memory
|
|
31
|
+
- ## Priorities
|
|
32
|
+
- ## Preferences
|
|
33
|
+
- ## Working Style
|
|
34
|
+
- ## Technical Defaults
|
|
35
|
+
- ## Communication Notes
|
|
36
|
+
- ## Repeated Workflows
|
|
37
|
+
- ## Constraints
|
|
38
|
+
|
|
39
|
+
JSON examples:
|
|
40
|
+
{"action":"none","reason":"Recent journals do not provide stable new user-profile evidence."}
|
|
41
|
+
|
|
42
|
+
{"action":"replace","reason":"Recent journals confirm a recurring workflow preference.","content":"# User Memory\n\n## Priorities\n..."}
|
|
@@ -40,7 +40,7 @@ from opencode_turns import (
|
|
|
40
40
|
)
|
|
41
41
|
|
|
42
42
|
_ANCHOR_RE = re.compile(r"<!-- session:([^ ]+) turn:([^ ]+) db:")
|
|
43
|
-
_TAIL_TURN_QUIET_PERIOD_MS =
|
|
43
|
+
_TAIL_TURN_QUIET_PERIOD_MS = int(os.environ.get("MEMSEARCH_OPENCODE_TAIL_QUIET_MS", "300000"))
|
|
44
44
|
|
|
45
45
|
|
|
46
46
|
class TailTurnObservation:
|
|
@@ -90,6 +90,38 @@ def get_plugin_summarize_model(memsearch_cmd: str | None = None) -> str:
|
|
|
90
90
|
return ""
|
|
91
91
|
|
|
92
92
|
|
|
93
|
+
def get_plugin_summarize_provider(memsearch_cmd: str | None = None) -> str:
|
|
94
|
+
"""Read the memsearch OpenCode summarize provider route."""
|
|
95
|
+
if not memsearch_cmd:
|
|
96
|
+
return ""
|
|
97
|
+
try:
|
|
98
|
+
result = subprocess.run(
|
|
99
|
+
[*split_memsearch_cmd(memsearch_cmd), "config", "get", "plugins.opencode.summarize.provider"],
|
|
100
|
+
capture_output=True,
|
|
101
|
+
text=True,
|
|
102
|
+
timeout=5,
|
|
103
|
+
)
|
|
104
|
+
return result.stdout.strip()
|
|
105
|
+
except Exception:
|
|
106
|
+
return ""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def get_plugin_summarize_enabled(memsearch_cmd: str | None = None) -> bool:
|
|
110
|
+
"""Read whether the memsearch OpenCode summarizer is enabled."""
|
|
111
|
+
if not memsearch_cmd:
|
|
112
|
+
return True
|
|
113
|
+
try:
|
|
114
|
+
result = subprocess.run(
|
|
115
|
+
[*split_memsearch_cmd(memsearch_cmd), "config", "get", "plugins.opencode.summarize.enabled"],
|
|
116
|
+
capture_output=True,
|
|
117
|
+
text=True,
|
|
118
|
+
timeout=5,
|
|
119
|
+
)
|
|
120
|
+
return result.stdout.strip().lower() != "false"
|
|
121
|
+
except Exception:
|
|
122
|
+
return True
|
|
123
|
+
|
|
124
|
+
|
|
93
125
|
def ensure_isolated_config() -> str:
|
|
94
126
|
"""Create isolated config dir without plugins/ to prevent recursion."""
|
|
95
127
|
isolated = os.path.expanduser("~/.codex/tmp/opencode-memsearch-summarize/opencode")
|
|
@@ -137,9 +169,36 @@ def _load_summarize_prompt(agent_name: str, memsearch_cmd: str | None = None) ->
|
|
|
137
169
|
|
|
138
170
|
|
|
139
171
|
def summarize_with_llm(turn_text: str, small_model: str, memsearch_cmd: str | None = None) -> str | None:
|
|
140
|
-
"""Summarize using
|
|
172
|
+
"""Summarize using configured provider routing."""
|
|
173
|
+
if not get_plugin_summarize_enabled(memsearch_cmd):
|
|
174
|
+
return None
|
|
175
|
+
|
|
141
176
|
system_prompt = _load_summarize_prompt("OpenCode", memsearch_cmd)
|
|
142
177
|
full_prompt = f"{system_prompt}\n\nTranscript:\n{turn_text}"
|
|
178
|
+
|
|
179
|
+
summarize_provider = get_plugin_summarize_provider(memsearch_cmd)
|
|
180
|
+
if summarize_provider and summarize_provider != "native" and memsearch_cmd:
|
|
181
|
+
try:
|
|
182
|
+
result = subprocess.run(
|
|
183
|
+
[*split_memsearch_cmd(memsearch_cmd), "summarize", "--plugin", "opencode", "--agent-name", "OpenCode"],
|
|
184
|
+
input=turn_text,
|
|
185
|
+
capture_output=True,
|
|
186
|
+
text=True,
|
|
187
|
+
timeout=30,
|
|
188
|
+
env={**os.environ, "MEMSEARCH_NO_WATCH": "1"},
|
|
189
|
+
)
|
|
190
|
+
output = result.stdout.strip()
|
|
191
|
+
lines = output.split("\n")
|
|
192
|
+
bullets = [line for line in lines if line.strip().startswith("- ")]
|
|
193
|
+
if bullets:
|
|
194
|
+
return "\n".join(bullets)
|
|
195
|
+
if output:
|
|
196
|
+
return output
|
|
197
|
+
except Exception:
|
|
198
|
+
pass
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
# Native path: summarize using opencode run in isolated env (no plugins -> no recursion).
|
|
143
202
|
isolated_dir = ensure_isolated_config()
|
|
144
203
|
|
|
145
204
|
summarize_model = get_plugin_summarize_model(memsearch_cmd) or small_model
|
|
@@ -427,6 +486,8 @@ def capture_session_turns(
|
|
|
427
486
|
# Check anchor first so that sidecar rebuilds repair state without
|
|
428
487
|
# calling the summarizer again for already-captured turns.
|
|
429
488
|
if not capture_exists(memory_dir, session_id, turn.turn_id):
|
|
489
|
+
if not get_plugin_summarize_enabled(memsearch_cmd):
|
|
490
|
+
continue
|
|
430
491
|
summary = summarize_with_llm(turn_text, small_model, memsearch_cmd)
|
|
431
492
|
write_capture(
|
|
432
493
|
memory_dir,
|
|
@@ -504,6 +565,12 @@ def main() -> None:
|
|
|
504
565
|
f"{args.memsearch_cmd} index '{memory_dir}' "
|
|
505
566
|
f"--collection {args.collection_name} &"
|
|
506
567
|
)
|
|
568
|
+
os.system(
|
|
569
|
+
f"python3 {shlex.quote(str(Path(__file__).resolve().parent / 'maintenance-runner.py'))} "
|
|
570
|
+
f"--platform opencode "
|
|
571
|
+
f"--project-dir {shlex.quote(args.project_dir)} "
|
|
572
|
+
f"--memsearch-dir {shlex.quote(os.path.join(args.project_dir, '.memsearch'))} &"
|
|
573
|
+
)
|
|
507
574
|
except Exception:
|
|
508
575
|
pass
|
|
509
576
|
finally:
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Plugin-local runner for MemSearch maintenance tasks.
|
|
3
|
+
|
|
4
|
+
This script belongs to the plugin layer. It handles host-native agent
|
|
5
|
+
invocations, while the Python package provides shared config, due-state,
|
|
6
|
+
prompt, and API-provider logic.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import contextlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import tempfile
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
DEFAULT_NATIVE_MODELS = {
|
|
22
|
+
"claude-code": "sonnet",
|
|
23
|
+
"codex": "",
|
|
24
|
+
"opencode": "",
|
|
25
|
+
"openclaw": "",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def run_command(cmd: list[str], *, env: dict[str, str], cwd: Path, timeout: int) -> str:
|
|
30
|
+
result = subprocess.run(
|
|
31
|
+
cmd,
|
|
32
|
+
capture_output=True,
|
|
33
|
+
text=True,
|
|
34
|
+
env=env,
|
|
35
|
+
cwd=str(cwd),
|
|
36
|
+
timeout=timeout,
|
|
37
|
+
check=False,
|
|
38
|
+
)
|
|
39
|
+
return (result.stdout or result.stderr or "").strip()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def extract_task_json_output(output: str) -> str:
|
|
43
|
+
"""Extract the first maintenance JSON object from noisy host output."""
|
|
44
|
+
for line in output.splitlines():
|
|
45
|
+
candidate = line.strip()
|
|
46
|
+
if not candidate.startswith("{"):
|
|
47
|
+
continue
|
|
48
|
+
try:
|
|
49
|
+
parsed = json.loads(candidate)
|
|
50
|
+
except json.JSONDecodeError:
|
|
51
|
+
continue
|
|
52
|
+
if isinstance(parsed, dict) and "action" in parsed:
|
|
53
|
+
return json.dumps(parsed, ensure_ascii=False)
|
|
54
|
+
return output
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def ensure_opencode_isolated_config() -> Path:
|
|
58
|
+
home = Path.home()
|
|
59
|
+
isolated = home / ".codex" / "tmp" / "opencode-memsearch-maintenance" / "opencode"
|
|
60
|
+
isolated.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
src = home / ".config" / "opencode" / "opencode.json"
|
|
62
|
+
if src.is_file():
|
|
63
|
+
shutil.copy2(src, isolated / "opencode.json")
|
|
64
|
+
return isolated
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def ensure_memsearch_importable() -> None:
|
|
68
|
+
user_paths = [
|
|
69
|
+
str(Path.home() / ".local" / "bin"),
|
|
70
|
+
str(Path.home() / ".cargo" / "bin"),
|
|
71
|
+
str(Path.home() / "bin"),
|
|
72
|
+
"/usr/local/bin",
|
|
73
|
+
]
|
|
74
|
+
existing_path = os.environ.get("PATH", "")
|
|
75
|
+
path_parts = existing_path.split(os.pathsep) if existing_path else []
|
|
76
|
+
for user_path in reversed(user_paths):
|
|
77
|
+
if Path(user_path).is_dir() and user_path not in path_parts:
|
|
78
|
+
path_parts.insert(0, user_path)
|
|
79
|
+
os.environ["PATH"] = os.pathsep.join(path_parts)
|
|
80
|
+
|
|
81
|
+
for parent in Path(__file__).resolve().parents:
|
|
82
|
+
src_dir = parent / "src"
|
|
83
|
+
if (src_dir / "memsearch").is_dir():
|
|
84
|
+
sys.path.insert(0, str(src_dir))
|
|
85
|
+
break
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
import memsearch # noqa: F401
|
|
89
|
+
|
|
90
|
+
return
|
|
91
|
+
except ModuleNotFoundError:
|
|
92
|
+
pass
|
|
93
|
+
|
|
94
|
+
if os.environ.get("MEMSEARCH_MAINTENANCE_UV_BOOTSTRAP") == "1":
|
|
95
|
+
return
|
|
96
|
+
|
|
97
|
+
memsearch_bin = shutil.which("memsearch")
|
|
98
|
+
if memsearch_bin:
|
|
99
|
+
with contextlib.suppress(OSError, UnicodeDecodeError):
|
|
100
|
+
first_line = Path(memsearch_bin).read_text(encoding="utf-8", errors="ignore").splitlines()[0]
|
|
101
|
+
if first_line.startswith("#!"):
|
|
102
|
+
python_bin = first_line[2:].strip().split()[0]
|
|
103
|
+
if python_bin:
|
|
104
|
+
os.execvpe(
|
|
105
|
+
python_bin,
|
|
106
|
+
[python_bin, str(Path(__file__).resolve()), *sys.argv[1:]],
|
|
107
|
+
{**os.environ, "MEMSEARCH_MAINTENANCE_UV_BOOTSTRAP": "1"},
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
uv = shutil.which("uv")
|
|
111
|
+
if not uv:
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
env = {**os.environ, "MEMSEARCH_MAINTENANCE_UV_BOOTSTRAP": "1"}
|
|
115
|
+
os.execvpe(
|
|
116
|
+
uv,
|
|
117
|
+
[
|
|
118
|
+
uv,
|
|
119
|
+
"run",
|
|
120
|
+
"--with",
|
|
121
|
+
"memsearch[onnx]",
|
|
122
|
+
"python",
|
|
123
|
+
str(Path(__file__).resolve()),
|
|
124
|
+
*sys.argv[1:],
|
|
125
|
+
],
|
|
126
|
+
env,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def apply_plugin_prompt_defaults(cfg) -> None:
|
|
131
|
+
plugin_dir = Path(__file__).resolve().parent.parent
|
|
132
|
+
prompts_dir = plugin_dir / "prompts"
|
|
133
|
+
for task in ("project_review", "user_profile"):
|
|
134
|
+
if getattr(cfg.prompts, task, ""):
|
|
135
|
+
continue
|
|
136
|
+
prompt_file = prompts_dir / f"{task}.txt"
|
|
137
|
+
if prompt_file.is_file():
|
|
138
|
+
setattr(cfg.prompts, task, str(prompt_file))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def run_native_provider(ctx, prompt: str) -> str:
|
|
142
|
+
model = ctx.task_config.model or DEFAULT_NATIVE_MODELS.get(ctx.platform, "")
|
|
143
|
+
env = {**os.environ, "MEMSEARCH_NO_WATCH": "1"}
|
|
144
|
+
|
|
145
|
+
if ctx.platform == "claude-code":
|
|
146
|
+
cmd = ["claude", "-p", "--strict-mcp-config", "--no-session-persistence", "--no-chrome"]
|
|
147
|
+
if model:
|
|
148
|
+
cmd += ["--model", model]
|
|
149
|
+
cmd += [
|
|
150
|
+
"--system-prompt",
|
|
151
|
+
"You are a maintenance task runner. Output only the requested JSON object.",
|
|
152
|
+
prompt,
|
|
153
|
+
]
|
|
154
|
+
env["CLAUDECODE"] = ""
|
|
155
|
+
return run_command(cmd, env=env, cwd=ctx.project_dir, timeout=120)
|
|
156
|
+
|
|
157
|
+
if ctx.platform == "codex":
|
|
158
|
+
with tempfile.NamedTemporaryFile(prefix="memsearch-codex-maintenance-", suffix=".txt", delete=False) as output_file:
|
|
159
|
+
output_path = Path(output_file.name)
|
|
160
|
+
cmd = [
|
|
161
|
+
"codex",
|
|
162
|
+
"exec",
|
|
163
|
+
"--ephemeral",
|
|
164
|
+
"--skip-git-repo-check",
|
|
165
|
+
"-s",
|
|
166
|
+
"read-only",
|
|
167
|
+
"-c",
|
|
168
|
+
"features.hooks=false",
|
|
169
|
+
"-c",
|
|
170
|
+
'model_reasoning_effort="medium"',
|
|
171
|
+
"-o",
|
|
172
|
+
str(output_path),
|
|
173
|
+
]
|
|
174
|
+
profile = os.environ.get("MEMSEARCH_CODEX_PROFILE", "").strip()
|
|
175
|
+
if profile:
|
|
176
|
+
cmd += ["-p", profile]
|
|
177
|
+
if model:
|
|
178
|
+
cmd += ["-m", model]
|
|
179
|
+
cmd.append(prompt)
|
|
180
|
+
env["MEMSEARCH_IN_STOP_WORKER"] = "1"
|
|
181
|
+
try:
|
|
182
|
+
run_command(cmd, env=env, cwd=ctx.project_dir, timeout=120)
|
|
183
|
+
return output_path.read_text(encoding="utf-8", errors="replace").strip()
|
|
184
|
+
finally:
|
|
185
|
+
output_path.unlink(missing_ok=True)
|
|
186
|
+
|
|
187
|
+
if ctx.platform == "openclaw":
|
|
188
|
+
cmd = ["openclaw", "agent", "--local", "--session-id", "memsearch-maintenance"]
|
|
189
|
+
if model:
|
|
190
|
+
cmd += ["--model", model]
|
|
191
|
+
cmd += ["-m", prompt]
|
|
192
|
+
env["MEMSEARCH_DISABLE"] = "1"
|
|
193
|
+
return extract_task_json_output(run_command(cmd, env=env, cwd=ctx.project_dir, timeout=120))
|
|
194
|
+
|
|
195
|
+
if ctx.platform == "opencode":
|
|
196
|
+
isolated = ensure_opencode_isolated_config()
|
|
197
|
+
cmd = ["opencode", "run"]
|
|
198
|
+
if model:
|
|
199
|
+
cmd += ["-m", model]
|
|
200
|
+
cmd.append(prompt)
|
|
201
|
+
env["XDG_CONFIG_HOME"] = str(isolated)
|
|
202
|
+
env["XDG_DATA_HOME"] = str(isolated / "data")
|
|
203
|
+
return run_command(cmd, env=env, cwd=ctx.project_dir, timeout=120)
|
|
204
|
+
|
|
205
|
+
raise RuntimeError(f"Unsupported native maintenance platform {ctx.platform!r}")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def main() -> int:
|
|
209
|
+
parser = argparse.ArgumentParser(description="Run plugin-local MemSearch maintenance tasks.")
|
|
210
|
+
parser.add_argument("--platform", required=True, choices=["claude-code", "codex", "opencode", "openclaw"])
|
|
211
|
+
parser.add_argument("--project-dir", default=None)
|
|
212
|
+
parser.add_argument("--memsearch-dir", default=None)
|
|
213
|
+
parser.add_argument("--force", action="store_true")
|
|
214
|
+
parser.add_argument("--json-output", action="store_true")
|
|
215
|
+
args = parser.parse_args()
|
|
216
|
+
|
|
217
|
+
old_cwd = Path.cwd()
|
|
218
|
+
try:
|
|
219
|
+
ensure_memsearch_importable()
|
|
220
|
+
from memsearch.config import resolve_config
|
|
221
|
+
from memsearch.maintenance import run_due_tasks, run_task_llm
|
|
222
|
+
|
|
223
|
+
project_dir = Path(args.project_dir or old_cwd).expanduser().resolve()
|
|
224
|
+
os.chdir(project_dir)
|
|
225
|
+
cfg = resolve_config()
|
|
226
|
+
apply_plugin_prompt_defaults(cfg)
|
|
227
|
+
|
|
228
|
+
def llm_runner(ctx, prompt: str) -> str:
|
|
229
|
+
provider_name = (ctx.task_config.provider or "native").strip()
|
|
230
|
+
if provider_name in {"", "native"}:
|
|
231
|
+
return run_native_provider(ctx, prompt)
|
|
232
|
+
return run_task_llm(ctx, prompt, cfg)
|
|
233
|
+
|
|
234
|
+
results = run_due_tasks(
|
|
235
|
+
platform=args.platform,
|
|
236
|
+
project_dir=project_dir,
|
|
237
|
+
memsearch_dir=args.memsearch_dir,
|
|
238
|
+
cfg=cfg,
|
|
239
|
+
force=args.force,
|
|
240
|
+
llm_runner=llm_runner,
|
|
241
|
+
)
|
|
242
|
+
except (KeyError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
|
|
243
|
+
sys.stderr.write(f"Maintenance error: {exc}\n")
|
|
244
|
+
return 1
|
|
245
|
+
finally:
|
|
246
|
+
with contextlib.suppress(OSError):
|
|
247
|
+
os.chdir(old_cwd)
|
|
248
|
+
|
|
249
|
+
payload = [result.__dict__ for result in results]
|
|
250
|
+
if args.json_output:
|
|
251
|
+
sys.stdout.write(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
|
|
252
|
+
else:
|
|
253
|
+
for result in results:
|
|
254
|
+
detail = f": {result.reason}" if result.reason else ""
|
|
255
|
+
sys.stdout.write(f"{result.task}: {result.action}{detail}\n")
|
|
256
|
+
return 0
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
if __name__ == "__main__":
|
|
260
|
+
raise SystemExit(main())
|
|
@@ -17,7 +17,7 @@ from dataclasses import dataclass, field
|
|
|
17
17
|
from pathlib import Path
|
|
18
18
|
|
|
19
19
|
|
|
20
|
-
@dataclass
|
|
20
|
+
@dataclass
|
|
21
21
|
class OpenCodeMessage:
|
|
22
22
|
"""A single meaningful OpenCode message with rendered text."""
|
|
23
23
|
|
|
@@ -29,7 +29,7 @@ class OpenCodeMessage:
|
|
|
29
29
|
text: str
|
|
30
30
|
|
|
31
31
|
|
|
32
|
-
@dataclass
|
|
32
|
+
@dataclass
|
|
33
33
|
class OpenCodeTurn:
|
|
34
34
|
"""A user turn plus its assistant follow-up messages."""
|
|
35
35
|
|
|
@@ -60,7 +60,7 @@ class OpenCodeTurn:
|
|
|
60
60
|
return "\n".join(lines).strip()
|
|
61
61
|
|
|
62
62
|
|
|
63
|
-
@dataclass
|
|
63
|
+
@dataclass
|
|
64
64
|
class TurnState:
|
|
65
65
|
"""Persistent capture progress for a session."""
|
|
66
66
|
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: memory-config
|
|
3
|
+
description: "Diagnose and configure MemSearch memory behavior for the OpenCode plugin. Use when the user asks about MemSearch configuration, plugin summarization, PROJECT.md/USER.md maintenance, memory directories, index health, provider routing, prompt files, or migration/compatibility questions."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
You are a MemSearch configuration assistant for the OpenCode plugin. This skill manages MemSearch settings only. It is not OpenCode's built-in memory configuration.
|
|
7
|
+
|
|
8
|
+
Start every user-facing answer with:
|
|
9
|
+
|
|
10
|
+
> This is MemSearch memory config, not OpenCode's own memory config.
|
|
11
|
+
|
|
12
|
+
When this skill is triggered, inspect the user's request text. If there is no concrete request, run a diagnostic. If they ask for a specific setting or change, route the request using the flows below.
|
|
13
|
+
|
|
14
|
+
## Intent Routing
|
|
15
|
+
|
|
16
|
+
- Empty request or "check": diagnose current MemSearch setup.
|
|
17
|
+
- "Show/get setting": read the requested resolved/global/project value.
|
|
18
|
+
- "Set/enable/disable/change": make a safe project-scoped change after confirming ambiguous choices.
|
|
19
|
+
- "Not capturing/search empty/no memory": troubleshoot files, config, and index health.
|
|
20
|
+
- "Use OpenAI/Gemini/Anthropic/native/model": configure provider routing.
|
|
21
|
+
- "PROJECT.md/USER.md/profile/review": configure advanced maintenance.
|
|
22
|
+
- "Prompt": explain or configure prompt overrides.
|
|
23
|
+
|
|
24
|
+
Ask the user before enabling external or paid providers, changing output paths, re-indexing, deleting state, or broadening what gets indexed.
|
|
25
|
+
|
|
26
|
+
## Diagnose First
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
memsearch config list --resolved
|
|
30
|
+
memsearch config list --global
|
|
31
|
+
memsearch config list --project
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
If `memsearch` is unavailable, try `uvx --from memsearch[onnx] memsearch --version`.
|
|
35
|
+
|
|
36
|
+
Check memory files:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
MDIR="${MEMSEARCH_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)/.memsearch}/memory"
|
|
40
|
+
ls -la "$MDIR"
|
|
41
|
+
find "$MDIR" -maxdepth 1 -type f -name '*.md' | sort | tail -10
|
|
42
|
+
tail -120 "$MDIR/$(date +%Y-%m-%d).md"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Check index health:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
memsearch stats
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
OpenCode transcript recall reads from OpenCode's SQLite database, while captured MemSearch memory lives as markdown under `.memsearch/memory/`.
|
|
52
|
+
|
|
53
|
+
## Background and Compatibility
|
|
54
|
+
|
|
55
|
+
Some plugin config fields may be missing or empty. That is usually normal:
|
|
56
|
+
|
|
57
|
+
- `summarize.enabled`, advanced maintenance, and task-specific provider/model fields are newer settings.
|
|
58
|
+
- Existing users' TOML files are not rewritten automatically after package/plugin upgrades.
|
|
59
|
+
- Empty strings usually mean "use the built-in or host-native default"; they do not necessarily mean "disabled" or "broken".
|
|
60
|
+
- Missing fields should be interpreted through `memsearch config list --resolved`, not by reading raw TOML alone.
|
|
61
|
+
- New users who run `memsearch config init` may see more fields than old users because the template includes newer options.
|
|
62
|
+
- Advanced maintenance is intentionally disabled by default to avoid surprise background model calls.
|
|
63
|
+
|
|
64
|
+
## Configuration Logic
|
|
65
|
+
|
|
66
|
+
Config is resolved from built-in defaults, global config, project config, env refs like `env:OPENAI_API_KEY`, and runtime env such as `MEMSEARCH_DIR`.
|
|
67
|
+
|
|
68
|
+
Use `memsearch config list --resolved` for effective behavior, `--global` for global overrides, and `--project` for repository-specific overrides.
|
|
69
|
+
|
|
70
|
+
Default recommendation:
|
|
71
|
+
|
|
72
|
+
- Put reusable defaults in global config so users do not repeat setup in every project.
|
|
73
|
+
- Put only project-specific overrides in project config.
|
|
74
|
+
- Use global config for named LLM providers, common model choices, normal input/output defaults, and shared prompt defaults.
|
|
75
|
+
- Use project config for one repo's enable/disable switches, unusual output files, special intervals, or repo-specific providers.
|
|
76
|
+
|
|
77
|
+
Maintenance `input_dir` and `output_file` may be relative even when configured globally. They are resolved from the current project directory at runtime. For custom prompt paths, prefer absolute paths in global config and relative paths in project config.
|
|
78
|
+
|
|
79
|
+
OpenCode plugin keys:
|
|
80
|
+
|
|
81
|
+
```toml
|
|
82
|
+
[plugins.opencode.summarize]
|
|
83
|
+
enabled = true
|
|
84
|
+
provider = "" # empty/native = OpenCode native summarizer
|
|
85
|
+
model = ""
|
|
86
|
+
|
|
87
|
+
[plugins.opencode.project_review]
|
|
88
|
+
enabled = false
|
|
89
|
+
provider = "native"
|
|
90
|
+
model = ""
|
|
91
|
+
min_interval_hours = 24
|
|
92
|
+
input_dir = ".memsearch/memory"
|
|
93
|
+
output_file = ".memsearch/PROJECT.md"
|
|
94
|
+
|
|
95
|
+
[plugins.opencode.user_profile]
|
|
96
|
+
enabled = false
|
|
97
|
+
provider = "native"
|
|
98
|
+
model = ""
|
|
99
|
+
min_interval_hours = 24
|
|
100
|
+
input_dir = ".memsearch/memory"
|
|
101
|
+
output_file = ".memsearch/USER.md"
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Provider rules:
|
|
105
|
+
|
|
106
|
+
- `provider = ""` or `native` uses OpenCode's non-interactive native path.
|
|
107
|
+
- Any other provider value is a name that must exist under `[llm.providers.<name>]`.
|
|
108
|
+
- Model resolution order is task-level `plugins.opencode.<task>.model`, then named provider model, then built-in default.
|
|
109
|
+
- API keys should be configured as env refs, not pasted into chat.
|
|
110
|
+
- If a raw TOML field is blank, check resolved config before calling it unset or broken.
|
|
111
|
+
|
|
112
|
+
Common provider examples:
|
|
113
|
+
|
|
114
|
+
```toml
|
|
115
|
+
[llm.providers.openai]
|
|
116
|
+
type = "openai"
|
|
117
|
+
model = "gpt-5-mini"
|
|
118
|
+
api_key = "env:OPENAI_API_KEY"
|
|
119
|
+
|
|
120
|
+
[llm.providers.anthropic]
|
|
121
|
+
type = "anthropic"
|
|
122
|
+
model = "claude-sonnet-4-6"
|
|
123
|
+
api_key = "env:ANTHROPIC_API_KEY"
|
|
124
|
+
|
|
125
|
+
[llm.providers.gemini]
|
|
126
|
+
type = "gemini"
|
|
127
|
+
model = "gemini-3-flash-preview"
|
|
128
|
+
api_key = "env:GEMINI_API_KEY"
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Model guidance:
|
|
132
|
+
|
|
133
|
+
- Normal turn summaries can use small/fast models. OpenCode native summarize uses OpenCode `small_model`, then its configured model/default behavior.
|
|
134
|
+
- Advanced maintenance needs better judgment. OpenCode native maintenance uses OpenCode's default unless `plugins.opencode.<task>.model` is set.
|
|
135
|
+
- For API providers, defaults are `openai -> gpt-5-mini`, `anthropic -> claude-sonnet-4-6`, and `gemini -> gemini-3-flash-preview`.
|
|
136
|
+
- If quality matters more than cost for maintenance, set `plugins.opencode.project_review.model` and `plugins.opencode.user_profile.model` explicitly.
|
|
137
|
+
|
|
138
|
+
Advanced maintenance runs after the plugin wakes it, only when enabled, journal input changed, and `min_interval_hours` elapsed. `PROJECT.md` and `USER.md` are maintenance artifacts by default and are not automatically indexed.
|
|
139
|
+
|
|
140
|
+
Before enabling advanced maintenance, ask which provider to use, whether the default 24-hour interval is acceptable, and whether `.memsearch/PROJECT.md` / `.memsearch/USER.md` are acceptable output files.
|
|
141
|
+
|
|
142
|
+
Prompt overrides:
|
|
143
|
+
|
|
144
|
+
```toml
|
|
145
|
+
[prompts]
|
|
146
|
+
summarize = ""
|
|
147
|
+
project_review = ""
|
|
148
|
+
user_profile = ""
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Empty prompt paths mean use the built-in MemSearch prompts. Custom prompt files may use `{{AGENT_NAME}}`, `{{TASK_NAME}}`, `{{PROJECT_DIR}}`, `{{INPUT_DIR}}`, and `{{OUTPUT_FILE}}`; the runner appends existing output, recent journals, and digest automatically.
|
|
152
|
+
|
|
153
|
+
Use `memsearch config set` for changes. After changing anything, show the command, the resolved value, and whether a new session is needed.
|
|
154
|
+
|
|
155
|
+
MemSearch TOML changes are read lazily by the CLI, capture daemon, and maintenance runner, so values such as `plugins.opencode.summarize.*`, `plugins.opencode.project_review.*`, `plugins.opencode.user_profile.*`, `[llm.providers.*]`, `[prompts]`, `milvus.*`, and `embedding.*` usually apply on the next capture, recall, index, or maintenance invocation. Restart OpenCode after `opencode.json` or plugin package changes; if capture behavior still looks stale after TOML edits, restart OpenCode or the capture daemon. After any answer, make clear that this is MemSearch memory configuration, not OpenCode's own memory/config system.
|
|
156
|
+
|
|
157
|
+
When useful, remind the user that they can either continue using this `memory-config` skill for guided configuration, or manually run `memsearch config init` for global interactive setup, `memsearch config init --project` for project interactive setup, and `memsearch config set/get/list` for direct CLI changes.
|