@memorax/memorax-code 0.1.8 → 0.1.10

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 (102) hide show
  1. package/README.md +10 -0
  2. package/bin/memorax-code-codebuddy.mjs +4 -0
  3. package/bin/memorax-code-setup.mjs +182 -65
  4. package/bin/memorax-code.mjs +74 -45
  5. package/docs/configuration.md +82 -22
  6. package/docs/troubleshooting.md +69 -5
  7. package/lib/automatic-update.mjs +233 -0
  8. package/lib/memorax-code-adapter-common/src/automatic-update-state.d.mts +24 -0
  9. package/lib/memorax-code-adapter-common/src/automatic-update-state.mjs +73 -0
  10. package/lib/memorax-code-adapter-common/src/clients/codebuddy-command.mjs +82 -0
  11. package/lib/memorax-code-adapter-common/src/config-utils.d.mts +2 -0
  12. package/lib/memorax-code-adapter-common/src/config-utils.mjs +11 -0
  13. package/lib/memorax-code-adapter-common/src/hooks/client-hook-launcher.mjs +3 -0
  14. package/lib/memorax-code-adapter-common/src/hooks/ensure-backend-runner.mjs +45 -10
  15. package/lib/memorax-code-adapter-common/src/repo-memory/repo-memory-job-worker.mjs +88 -3
  16. package/lib/memorax-code-adapter-common/src/windows-cli-invocation.mjs +11 -1
  17. package/lib/memorax-code-backend/dist/app/backend-server.js +2 -2
  18. package/lib/memorax-code-backend/dist/app/memory-observability.js +2 -2
  19. package/lib/memorax-code-backend/dist/clients/codebuddy/jsonl-history.js +208 -0
  20. package/lib/memorax-code-backend/dist/clients/codebuddy/lifecycle.js +44 -0
  21. package/lib/memorax-code-backend/dist/clients/codebuddy/memory-hook-runtime.js +250 -0
  22. package/lib/memorax-code-backend/dist/clients/codebuddy/turn-id.js +16 -0
  23. package/lib/memorax-code-backend/dist/clients/codex/plugin-install.js +129 -7
  24. package/lib/memorax-code-backend/dist/clients/codex/rollout-turn.js +52 -2
  25. package/lib/memorax-code-backend/dist/config/memorax-code.js +14 -1
  26. package/lib/memorax-code-backend/dist/entrypoints/backend-cli.js +43 -6
  27. package/lib/memorax-code-backend/dist/lifecycle/active-clients.js +3 -0
  28. package/lib/memorax-code-backend/dist/lifecycle/automatic-update-scheduler.js +133 -0
  29. package/lib/memorax-code-backend/dist/lifecycle/client-plugin-removal.js +14 -2
  30. package/lib/memorax-code-backend/dist/lifecycle/client-selection.js +6 -4
  31. package/lib/memorax-code-backend/dist/lifecycle/orchestrator.js +48 -9
  32. package/lib/memorax-code-backend/dist/memory/cli.js +4 -2
  33. package/lib/memorax-code-backend/dist/memory/hook-command.js +31 -1
  34. package/lib/memorax-code-backend/dist/memory/reminder-trace-recorder.js +5 -1
  35. package/lib/memorax-code-backend/dist/memory/service.js +12 -0
  36. package/lib/memorax-code-backend/dist/shared/windows-cli-invocation.js +10 -1
  37. package/lib/memorax-code-backend/dist/trace/config.js +12 -0
  38. package/lib/memorax-code-backend/dist/trace/context.js +21 -1
  39. package/lib/memorax-code-backend/dist/trace/store.js +12 -1
  40. package/lib/memorax-code-backend/package.json +1 -1
  41. package/lib/memorax-code-claude-adapter/.claude-plugin/plugin.json +1 -1
  42. package/lib/memorax-code-claude-adapter/hooks/runtime-shell.json +1 -1
  43. package/lib/memorax-code-claude-adapter/package.json +1 -1
  44. package/lib/memorax-code-claude-adapter/runtime-hooks/ensure-backend.mjs +2 -0
  45. package/lib/memorax-code-claude-adapter/src/plugin-install.mjs +3 -0
  46. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/.claude-plugin/plugin.json +1 -1
  47. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/hooks/runtime-shell.json +1 -1
  48. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/memorax-code-adapter-common/src/automatic-update-state.d.mts +24 -0
  49. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/memorax-code-adapter-common/src/automatic-update-state.mjs +73 -0
  50. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/memorax-code-adapter-common/src/clients/codebuddy-command.mjs +82 -0
  51. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/memorax-code-adapter-common/src/config-utils.d.mts +2 -0
  52. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/memorax-code-adapter-common/src/config-utils.mjs +11 -0
  53. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/memorax-code-adapter-common/src/hooks/client-hook-launcher.mjs +3 -0
  54. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/memorax-code-adapter-common/src/hooks/ensure-backend-runner.mjs +45 -10
  55. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/memorax-code-adapter-common/src/repo-memory/repo-memory-job-worker.mjs +88 -3
  56. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/memorax-code-adapter-common/src/windows-cli-invocation.mjs +11 -1
  57. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/package.json +1 -1
  58. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/runtime-hooks/ensure-backend.mjs +2 -0
  59. package/lib/memorax-code-claude-marketplace/plugins/memorax-code-claude-adapter/src/plugin-install.mjs +3 -0
  60. package/lib/memorax-code-codebuddy-adapter/.codebuddy-plugin/plugin.json +7 -0
  61. package/lib/memorax-code-codebuddy-adapter/hooks/common-runtime.mjs +13 -0
  62. package/lib/memorax-code-codebuddy-adapter/hooks/hooks.json +38 -0
  63. package/lib/memorax-code-codebuddy-adapter/hooks/repo-memory-job.mjs +40 -0
  64. package/lib/memorax-code-codebuddy-adapter/hooks/runtime-hook.mjs +279 -0
  65. package/lib/memorax-code-codebuddy-adapter/package.json +9 -0
  66. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/SKILL.md +85 -0
  67. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/agents/claude.yaml +10 -0
  68. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/agents/openai.yaml +7 -0
  69. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/defaults.json +12 -0
  70. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/references/memorax-add.md +88 -0
  71. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/references/memorax-search.md +93 -0
  72. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/references/personal-read.md +46 -0
  73. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/references/personal-write.md +120 -0
  74. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/references/repo-build.md +319 -0
  75. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/references/repo-read.md +103 -0
  76. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/references/repo-templates.md +390 -0
  77. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/references/repo-update.md +127 -0
  78. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/scripts/collect_all.py +579 -0
  79. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/scripts/detect_updates.py +919 -0
  80. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/scripts/git_commit_facets.py +222 -0
  81. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/scripts/github_resource_facets.py +512 -0
  82. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/scripts/gitlab_resource_facets.py +517 -0
  83. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/scripts/prepare_repo_memory.py +411 -0
  84. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/scripts/user_profile_memory.py +528 -0
  85. package/lib/memorax-code-codebuddy-adapter/skills/memorax-code/scripts/validate_memory.py +248 -0
  86. package/lib/memorax-code-codebuddy-adapter/src/cli.mjs +58 -0
  87. package/lib/memorax-code-codebuddy-adapter/src/config.mjs +277 -0
  88. package/lib/memorax-code-codebuddy-adapter/src/hook-manifest.mjs +47 -0
  89. package/lib/memorax-code-codebuddy-adapter/src/runtime-observation.mjs +65 -0
  90. package/lib/memorax-code-codex-adapter/.codex-plugin/plugin.json +1 -1
  91. package/lib/memorax-code-codex-adapter/hooks/runtime-shell.json +1 -1
  92. package/lib/memorax-code-codex-adapter/package.json +1 -1
  93. package/lib/memorax-code-codex-adapter/runtime-hooks/ensure-backend.mjs +4 -1
  94. package/lib/memorax-code-dsh-adapter/package.json +2 -1
  95. package/lib/memorax-code-dsh-adapter/src/profile-lifecycle.mjs +1 -0
  96. package/lib/memorax-code-opencode-adapter/package.json +1 -1
  97. package/lib/npm-invocation.mjs +51 -8
  98. package/lib/resolve-codebuddy-command.mjs +112 -0
  99. package/lib/run-entrypoint.mjs +25 -1
  100. package/lib/windows-cli-invocation.mjs +11 -1
  101. package/lib/windows-user-path.mjs +218 -0
  102. package/package.json +5 -3
@@ -0,0 +1,248 @@
1
+ #!/usr/bin/env python3
2
+ """Validate authored repo-memory bundles."""
3
+
4
+ import argparse
5
+ import json
6
+ import re
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ BASELINE_FILES = [
13
+ Path("PROFILE.md"),
14
+ Path("resources/commits.md"),
15
+ Path("resources/prs.md"),
16
+ Path("resources/issues.md"),
17
+ Path("raw/git-commits.json"),
18
+ ]
19
+
20
+ PROVIDER_RAW_FILES = [Path("raw/github-facets.json"), Path("raw/gitlab-facets.json")]
21
+ PROVIDER_RESOURCE_FILES = [Path("resources/prs.md"), Path("resources/issues.md")]
22
+ DISABLED_RESOURCE_SOURCES = {"history_disabled", "provider_skipped_local_only", "provider_unavailable", "github_resource_facets_unavailable", "gitlab_resource_facets_unavailable", "provider_unavailable_local_only"}
23
+ USER_PROFILE_SIDECAR = Path("user-profile/preferences.md")
24
+ PROCEDURE_SIDECAR_DIRECTORY = "procedure-memory"
25
+ PLACEHOLDER_RE = re.compile(r"\[([^\]\n]+)\]")
26
+ LINK_TARGET_AFTER_BRACKET_RE = re.compile(r"[ \t\r\n]*\(")
27
+
28
+
29
+ def relative(path: Path, memory: Path) -> str:
30
+ return path.relative_to(memory).as_posix()
31
+
32
+
33
+ def resolve_memory_root(path: Path) -> Path:
34
+ candidate = path.expanduser().resolve()
35
+ if candidate.name == ".repo_memory":
36
+ return candidate
37
+ return candidate / ".repo_memory"
38
+
39
+
40
+ def parse_frontmatter(text: str) -> dict[str, Any]:
41
+ if not text.startswith("---\n"):
42
+ return {}
43
+ end = text.find("\n---", 4)
44
+ if end == -1:
45
+ return {}
46
+ values: dict[str, Any] = {}
47
+ for line in text[4:end].splitlines():
48
+ if ":" not in line:
49
+ continue
50
+ key, value = line.split(":", 1)
51
+ key = key.strip()
52
+ value = value.strip()
53
+ if not key:
54
+ continue
55
+ if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")):
56
+ values[key] = value[1:-1]
57
+ elif re.fullmatch(r"-?\d+", value):
58
+ values[key] = int(value)
59
+ elif value.lower() == "true":
60
+ values[key] = True
61
+ elif value.lower() == "false":
62
+ values[key] = False
63
+ else:
64
+ values[key] = value
65
+ return values
66
+
67
+
68
+ def body_after_frontmatter(text: str) -> str:
69
+ if not text.startswith("---\n"):
70
+ return text
71
+ end = text.find("\n---", 4)
72
+ if end == -1:
73
+ return text
74
+ return text[end + 4 :].lstrip("\n")
75
+
76
+
77
+ def item_section_count(text: str) -> int:
78
+ body = body_after_frontmatter(text)
79
+ lines = body.splitlines()
80
+ title_seen = False
81
+ count = 0
82
+ for line in lines:
83
+ if line.startswith("# ") and not title_seen:
84
+ title_seen = True
85
+ continue
86
+ if title_seen and line.startswith("## "):
87
+ count += 1
88
+ return count
89
+
90
+
91
+ def placeholder_matches(text: str) -> list[str]:
92
+ text = strip_markdown_code(text)
93
+ matches: list[str] = []
94
+ for match in PLACEHOLDER_RE.finditer(text):
95
+ if LINK_TARGET_AFTER_BRACKET_RE.match(text, match.end()):
96
+ continue
97
+ value = match.group(1).strip()
98
+ if not value or value.startswith("#"):
99
+ continue
100
+ if re.search(r"[A-Za-z]", value):
101
+ matches.append(f"[{value}]")
102
+ return matches
103
+
104
+
105
+ def strip_markdown_code(text: str) -> str:
106
+ without_fences = re.sub(r"```.*?```", "", text, flags=re.DOTALL)
107
+ return re.sub(r"`[^`\n]*`", "", without_fences)
108
+
109
+
110
+ def check_exists(memory: Path, rel_path: Path, errors: list[str], checked: list[str]) -> bool:
111
+ path = memory / rel_path
112
+ checked.append(rel_path.as_posix())
113
+ if not path.exists():
114
+ errors.append(f"{rel_path.as_posix()}: required file is missing")
115
+ return False
116
+ if not path.is_file():
117
+ errors.append(f"{rel_path.as_posix()}: expected a file")
118
+ return False
119
+ return True
120
+
121
+
122
+ def validate_json(path: Path, memory: Path, errors: list[str], checked: list[str]) -> None:
123
+ checked.append(relative(path, memory))
124
+ try:
125
+ json.loads(path.read_text(encoding="utf-8"))
126
+ except json.JSONDecodeError as exc:
127
+ errors.append(f"{relative(path, memory)}: invalid JSON at line {exc.lineno}, column {exc.colno}: {exc.msg}")
128
+ except OSError as exc:
129
+ errors.append(f"{relative(path, memory)}: could not read JSON: {exc}")
130
+
131
+
132
+ def raw_source_points_to_provider(raw_source: Any) -> bool:
133
+ return isinstance(raw_source, str) and raw_source.endswith(("github-facets.json", "gitlab-facets.json"))
134
+
135
+
136
+ def validate_markdown(path: Path, memory: Path, errors: list[str], warnings: list[str], checked: list[str]) -> None:
137
+ checked.append(relative(path, memory))
138
+ try:
139
+ text = path.read_text(encoding="utf-8")
140
+ except OSError as exc:
141
+ errors.append(f"{relative(path, memory)}: could not read Markdown: {exc}")
142
+ return
143
+
144
+ frontmatter = parse_frontmatter(text)
145
+ rel = relative(path, memory)
146
+ if not frontmatter.get("schema"):
147
+ errors.append(f"{rel}: frontmatter field 'schema' is missing")
148
+
149
+ placeholders = placeholder_matches(text)
150
+ if placeholders:
151
+ errors.append(f"{rel}: unresolved bracket placeholder(s): {', '.join(placeholders)}")
152
+
153
+ if path.parent.name != "resources":
154
+ return
155
+
156
+ for field in ["source", "resource_count", "trust_state", "raw_source"]:
157
+ if field not in frontmatter:
158
+ errors.append(f"{rel}: frontmatter field '{field}' is missing")
159
+
160
+ expected = frontmatter.get("resource_count")
161
+ actual = item_section_count(text)
162
+ if isinstance(expected, int):
163
+ if expected != actual:
164
+ errors.append(f"{rel}: resource_count is {expected}, but found {actual} item section(s)")
165
+ elif expected is not None:
166
+ errors.append(f"{rel}: resource_count must be an integer")
167
+
168
+ source = frontmatter.get("source")
169
+ raw_source = frontmatter.get("raw_source")
170
+ if "source" in frontmatter and not source:
171
+ errors.append(f"{rel}: frontmatter field 'source' must not be empty")
172
+ if "trust_state" in frontmatter and not frontmatter.get("trust_state"):
173
+ errors.append(f"{rel}: frontmatter field 'trust_state' must not be empty")
174
+ if source in DISABLED_RESOURCE_SOURCES and isinstance(expected, int) and expected != 0:
175
+ errors.append(f"{rel}: disabled or unavailable resource source {source!r} must use resource_count 0")
176
+ if source in DISABLED_RESOURCE_SOURCES and raw_source:
177
+ errors.append(f"{rel}: disabled or unavailable resource source {source!r} must use an empty raw_source")
178
+ if path.name in {"commits.md", "prs.md", "issues.md"} and source not in DISABLED_RESOURCE_SOURCES and raw_source == "":
179
+ errors.append(f"{rel}: empty raw_source requires a disabled or unavailable source")
180
+ if path.name in {"prs.md", "issues.md"} and raw_source_points_to_provider(raw_source):
181
+ provider_path = (path.parent / raw_source).resolve()
182
+ if not provider_path.exists():
183
+ errors.append(f"{rel}: provider raw evidence is missing for raw_source {raw_source!r}")
184
+
185
+
186
+ def provider_raw_paths(memory: Path) -> list[Path]:
187
+ return [memory / rel for rel in PROVIDER_RAW_FILES if (memory / rel).exists()]
188
+
189
+
190
+ def validate(memory: Path) -> dict[str, Any]:
191
+ errors: list[str] = []
192
+ warnings: list[str] = []
193
+ checked: list[str] = []
194
+
195
+ if not memory.exists():
196
+ errors.append(f"{memory}: .repo_memory directory is missing")
197
+ return {"ok": False, "errors": errors, "warnings": warnings, "checked": checked}
198
+ if not memory.is_dir():
199
+ errors.append(f"{memory}: expected .repo_memory to be a directory")
200
+ return {"ok": False, "errors": errors, "warnings": warnings, "checked": checked}
201
+
202
+ for rel_path in BASELINE_FILES:
203
+ check_exists(memory, rel_path, errors, checked)
204
+
205
+ markdown_paths = sorted(
206
+ path
207
+ for path in memory.rglob("*.md")
208
+ if path.is_file()
209
+ and path.relative_to(memory) != USER_PROFILE_SIDECAR
210
+ and path.relative_to(memory).parts[0] != PROCEDURE_SIDECAR_DIRECTORY
211
+ )
212
+ for path in markdown_paths:
213
+ if path.exists() and path.is_file():
214
+ validate_markdown(path, memory, errors, warnings, checked)
215
+
216
+ json_paths = sorted(path for path in (memory / "raw").rglob("*.json") if path.is_file())
217
+ provider_raw = provider_raw_paths(memory)
218
+
219
+ if provider_raw:
220
+ for rel_path in PROVIDER_RESOURCE_FILES:
221
+ check_exists(memory, rel_path, errors, checked)
222
+
223
+ seen_json: set[Path] = set()
224
+ for path in json_paths:
225
+ if path.exists() and path.is_file() and path not in seen_json:
226
+ seen_json.add(path)
227
+ validate_json(path, memory, errors, checked)
228
+
229
+ checked = sorted(dict.fromkeys(checked))
230
+ return {"ok": not errors, "errors": errors, "warnings": warnings, "checked": checked}
231
+
232
+
233
+ def parse_args(argv: list[str]) -> argparse.Namespace:
234
+ parser = argparse.ArgumentParser(description="Validate a repo-memory bundle.")
235
+ parser.add_argument("path", help="Path to a repository or its .repo_memory directory")
236
+ parser.add_argument("--pretty", action="store_true", help="Pretty-print JSON output")
237
+ return parser.parse_args(argv)
238
+
239
+
240
+ def main(argv: list[str]) -> int:
241
+ args = parse_args(argv)
242
+ report = validate(resolve_memory_root(Path(args.path)))
243
+ print(json.dumps(report, ensure_ascii=False, indent=2 if args.pretty else None))
244
+ return 0 if report["ok"] else 1
245
+
246
+
247
+ if __name__ == "__main__":
248
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ defaultCodeBuddyHome,
4
+ disableCodeBuddyAdapter,
5
+ enableCodeBuddyAdapter,
6
+ readCodeBuddyAdapterStatus,
7
+ removeCodeBuddyPluginInstallation,
8
+ } from "./config.mjs";
9
+
10
+ try {
11
+ const parsed = parseCli(process.argv);
12
+ if (parsed.help) {
13
+ console.log("Usage: memorax-code-codebuddy [status|enable|disable|remove] [--codebuddy-home DIR] [--json]");
14
+ process.exit(0);
15
+ }
16
+ const options = { codeBuddyHome: parsed.home };
17
+ const result = parsed.command === "status"
18
+ ? await readCodeBuddyAdapterStatus(options)
19
+ : parsed.command === "enable"
20
+ ? await enableCodeBuddyAdapter(options)
21
+ : parsed.command === "disable"
22
+ ? await disableCodeBuddyAdapter(options)
23
+ : parsed.command === "remove"
24
+ ? await removeCodeBuddyPluginInstallation(options)
25
+ : undefined;
26
+ if (!result) throw new Error(`unknown command: ${parsed.command}`);
27
+ if (parsed.json) console.log(JSON.stringify(result, null, 2));
28
+ else console.log(`${result.action}: ${result.ok ? "ok" : "failed"}\nhome: ${result.codeBuddyHome ?? parsed.home}`);
29
+ const ready = result.ok === true
30
+ && result.installed === true
31
+ && result.enabled === true
32
+ && result.marketplaceReady === true
33
+ && result.codebuddyHooks?.ok === true
34
+ && result.codebuddySkills?.ok === true;
35
+ process.exit(parsed.command === "status" ? (ready ? 0 : 1) : (result.ok ? 0 : 1));
36
+ } catch (error) {
37
+ console.error(error instanceof Error ? error.message : String(error));
38
+ process.exit(1);
39
+ }
40
+
41
+ function parseCli(argv) {
42
+ const args = argv.slice(2);
43
+ const command = args[0] && !args[0].startsWith("-") ? args.shift() : "status";
44
+ let home;
45
+ let json = false;
46
+ for (let index = 0; index < args.length; index += 1) {
47
+ const arg = args[index];
48
+ if (arg === "--help") return { command, help: true };
49
+ if (arg === "--json") { json = true; continue; }
50
+ if (arg === "--codebuddy-home") {
51
+ home = args[++index];
52
+ if (!home || home.startsWith("--")) throw new Error("--codebuddy-home requires a value");
53
+ continue;
54
+ }
55
+ throw new Error(`unknown option: ${arg}`);
56
+ }
57
+ return { command, home: home ?? defaultCodeBuddyHome(), json, help: false };
58
+ }
@@ -0,0 +1,277 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { chmod, cp, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, relative, sep, win32 } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { resolveHookCodeBuddyCommand } from "../../memorax-code-adapter-common/src/clients/codebuddy-command.mjs";
7
+ import {
8
+ codeBuddyHookManifestConfigured,
9
+ materializeCodeBuddyHookManifest,
10
+ } from "./hook-manifest.mjs";
11
+ import {
12
+ codeBuddyRuntimeObservationPath,
13
+ readCodeBuddyRuntimeObservation,
14
+ } from "./runtime-observation.mjs";
15
+
16
+ const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
17
+ const VERSION = readPluginVersion();
18
+ const PLUGIN_NAME = "memorax-code-codebuddy-adapter";
19
+ const MARKETPLACE_NAME = "memorax-code-local";
20
+ const PLUGIN_ID = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;
21
+
22
+ export function defaultCodeBuddyHome(env = process.env, homeDir = homedir(), platform = process.platform) {
23
+ return env.CODEBUDDY_HOME?.trim()
24
+ || env.WORKBUDDY_HOME?.trim()
25
+ || (platform === "win32" ? win32.join(homeDir, ".codebuddy") : join(homeDir, ".workbuddy"));
26
+ }
27
+ // CodeBuddy stores installed plugin caches under the marketplace namespace.
28
+ export function codeBuddyInstallPath(home = defaultCodeBuddyHome()) { return join(home, "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME, VERSION); }
29
+ export function installedRegistryPath(home = defaultCodeBuddyHome()) { return join(home, "plugins", "installed_plugins.json"); }
30
+ export function codeBuddySettingsPath(home = defaultCodeBuddyHome()) { return join(home, "settings.json"); }
31
+ export function knownMarketplacesPath(home = defaultCodeBuddyHome()) { return join(home, "plugins", "known_marketplaces.json"); }
32
+ export function marketplaceRoot(home = defaultCodeBuddyHome()) { return join(home, "plugins", "marketplaces", MARKETPLACE_NAME); }
33
+ export function marketplacePluginPath(home = defaultCodeBuddyHome()) { return join(marketplaceRoot(home), "plugins", PLUGIN_NAME); }
34
+
35
+ export async function enableCodeBuddyAdapter(options = {}) {
36
+ const home = options.codeBuddyHome ?? defaultCodeBuddyHome();
37
+ const platform = options.platform ?? process.platform;
38
+ const memoraxCodeHome = options.memoraxCodeHome ?? defaultMemoraxCodeHome();
39
+ const installPath = options.installPath ?? codeBuddyInstallPath(home);
40
+ const localPluginPath = marketplacePluginPath(home);
41
+ await rm(codeBuddyRuntimeObservationPath(memoraxCodeHome), { force: true });
42
+ await mkdir(dirname(installPath), { recursive: true });
43
+ await rm(installPath, { recursive: true, force: true });
44
+ await rm(legacyCodeBuddyInstallPath(home), { recursive: true, force: true });
45
+ await cp(ROOT, installPath, { recursive: true, force: true, filter: packageCopyFilter(ROOT) });
46
+ await materializeCommonRuntime(installPath);
47
+ await materializeCodeBuddyHookManifest(installPath, platform);
48
+ await writePackageMetadata(installPath, options.codeBuddyCommand, home);
49
+ await materializeCanonicalSkill(installPath);
50
+ await mkdir(dirname(localPluginPath), { recursive: true });
51
+ await rm(localPluginPath, { recursive: true, force: true });
52
+ await cp(ROOT, localPluginPath, { recursive: true, force: true, filter: packageCopyFilter(ROOT) });
53
+ await materializeCommonRuntime(localPluginPath);
54
+ await materializeCodeBuddyHookManifest(localPluginPath, platform);
55
+ await writePackageMetadata(localPluginPath, options.codeBuddyCommand, home);
56
+ await materializeCanonicalSkill(localPluginPath);
57
+ await writeMarketplaceManifest(home);
58
+ await updateKnownMarketplace(home, true);
59
+ await updateSettings(home, (settings) => {
60
+ settings.enabledPlugins = recordValue(settings.enabledPlugins);
61
+ settings.enabledPlugins[PLUGIN_ID] = true;
62
+ });
63
+ await updateLegacyRegistry(home, { installPath, enabled: true });
64
+ return { ok: true, action: "enable", runtime: "codebuddy", integration: "hooks", installed: true, enabled: true, codeBuddyHome: home, installPath, marketplace: MARKETPLACE_NAME, pluginId: PLUGIN_ID, marketplacePath: localPluginPath, codebuddyHooks: { ok: true, configured: true, runtimeObserved: false, status: "unverified" }, codebuddySkills: { ok: true, status: "installed", managed: true, memoraxCode: true, path: join(localPluginPath, "skills", "memorax-code", "SKILL.md") } };
65
+ }
66
+
67
+ export async function disableCodeBuddyAdapter(options = {}) {
68
+ const home = options.codeBuddyHome ?? defaultCodeBuddyHome();
69
+ const registryPath = installedRegistryPath(home);
70
+ const installed = await pathExists(marketplacePluginPath(home)) || await pathExists(codeBuddyInstallPath(home));
71
+ if (!installed) return { ok: true, action: "disable", runtime: "codebuddy", installed: false, enabled: false, codeBuddyHome: home, statePath: registryPath, marketplace: MARKETPLACE_NAME, pluginId: PLUGIN_ID };
72
+ await updateSettings(home, (settings) => {
73
+ settings.enabledPlugins = recordValue(settings.enabledPlugins);
74
+ settings.enabledPlugins[PLUGIN_ID] = false;
75
+ });
76
+ await updateLegacyRegistry(home, { installPath: codeBuddyInstallPath(home), enabled: false });
77
+ return { ok: true, action: "disable", runtime: "codebuddy", installed: true, enabled: false, codeBuddyHome: home, statePath: registryPath, marketplace: MARKETPLACE_NAME, pluginId: PLUGIN_ID };
78
+ }
79
+
80
+ export async function readCodeBuddyAdapterStatus(options = {}) {
81
+ const home = options.codeBuddyHome ?? defaultCodeBuddyHome();
82
+ const platform = options.platform ?? process.platform;
83
+ const memoraxCodeHome = options.memoraxCodeHome ?? defaultMemoraxCodeHome();
84
+ const installPath = codeBuddyInstallPath(home);
85
+ const localPluginPath = marketplacePluginPath(home);
86
+ const settings = await readJsonRecord(codeBuddySettingsPath(home));
87
+ const known = await readJsonRecord(knownMarketplacesPath(home));
88
+ const installedRoots = [];
89
+ for (const root of [localPluginPath, installPath]) {
90
+ if (await pathExists(root)) installedRoots.push(root);
91
+ }
92
+ const installed = installedRoots.length > 0;
93
+ const skillPath = join(localPluginPath, "skills", "memorax-code", "SKILL.md");
94
+ const skillInstalled = await pathExists(skillPath);
95
+ const enabled = settings.enabledPlugins?.[PLUGIN_ID] === true;
96
+ const marketplaceReady = Boolean(known[MARKETPLACE_NAME]);
97
+ const hookConfigured = installedRoots.length > 0
98
+ && (await Promise.all(installedRoots.map((root) => codeBuddyHookManifestConfigured(root, platform)))).every(Boolean);
99
+ const observation = await readCodeBuddyRuntimeObservation(memoraxCodeHome);
100
+ const runtimeObserved = hookConfigured && observationMatches(observation, home, platform);
101
+ return { ok: true, action: "status", runtime: "codebuddy", integration: "hooks", installed, enabled, managed: installed && marketplaceReady, codeBuddyHome: home, installPath, marketplace: MARKETPLACE_NAME, pluginId: PLUGIN_ID, marketplaceReady, codebuddyHooks: { ok: hookConfigured, configured: hookConfigured, runtimeObserved, status: hookConfigured ? (runtimeObserved ? "observed" : "unverified") : "invalid", observationPath: codeBuddyRuntimeObservationPath(memoraxCodeHome) }, codebuddySkills: { ok: skillInstalled, status: skillInstalled ? "installed" : "missing", managed: skillInstalled, memoraxCode: skillInstalled, path: skillPath } };
102
+ }
103
+
104
+ export async function removeCodeBuddyPluginInstallation(options = {}) {
105
+ const home = options.codeBuddyHome ?? defaultCodeBuddyHome();
106
+ const installed = await pathExists(marketplacePluginPath(home)) || await pathExists(codeBuddyInstallPath(home));
107
+ if (!installed) return { ok: true, action: "codebuddy-plugin-remove", runtime: "codebuddy", installed: false, enabled: false, removed: false, codeBuddyHome: home, marketplace: MARKETPLACE_NAME, pluginId: PLUGIN_ID };
108
+ const status = await disableCodeBuddyAdapter({ codeBuddyHome: home });
109
+ await updateSettings(home, (settings) => {
110
+ settings.enabledPlugins = recordValue(settings.enabledPlugins);
111
+ delete settings.enabledPlugins[PLUGIN_ID];
112
+ });
113
+ await updateKnownMarketplace(home, false);
114
+ await updateRegistry(home, (registry) => { delete registry[PLUGIN_ID]; });
115
+ await rm(codeBuddyInstallPath(home), { recursive: true, force: true });
116
+ await rm(legacyCodeBuddyInstallPath(home), { recursive: true, force: true });
117
+ await rm(marketplaceRoot(home), { recursive: true, force: true });
118
+ return { ...status, action: "codebuddy-plugin-remove", installed: false, enabled: false, removed: true };
119
+ }
120
+
121
+ async function readRegistry(home) {
122
+ try {
123
+ const value = JSON.parse(await readFile(installedRegistryPath(home), "utf8"));
124
+ if (value?.plugins && typeof value.plugins === "object" && !Array.isArray(value.plugins)) return value.plugins;
125
+ throw new Error(`invalid CodeBuddy plugin registry: ${installedRegistryPath(home)}`);
126
+ } catch (error) {
127
+ if (error?.code === "ENOENT") return {};
128
+ throw error;
129
+ }
130
+ }
131
+ async function writeRegistry(home, plugins) { await writeJsonFile(installedRegistryPath(home), { version: 2, plugins }); }
132
+ async function updateLegacyRegistry(home, { installPath, enabled }) {
133
+ await updateRegistry(home, (registry) => {
134
+ registry[PLUGIN_ID] = [{ scope: "user", installPath, version: VERSION, enabled, installedAt: new Date().toISOString(), lastUpdated: new Date().toISOString() }];
135
+ });
136
+ }
137
+ async function writeMarketplaceManifest(home) {
138
+ const path = join(marketplaceRoot(home), ".codebuddy-plugin", "marketplace.json");
139
+ await writeJsonFile(path, {
140
+ name: MARKETPLACE_NAME,
141
+ description: "MemoraX Code local integration marketplace",
142
+ plugins: [{ name: PLUGIN_NAME, source: `./plugins/${PLUGIN_NAME}`, version: VERSION, description: "MemoraX Code memory integration for CodeBuddy and WorkBuddy." }],
143
+ });
144
+ }
145
+ async function updateKnownMarketplace(home, enabled) {
146
+ const path = knownMarketplacesPath(home);
147
+ const known = await readJsonRecord(path);
148
+ if (enabled) {
149
+ known[MARKETPLACE_NAME] = {
150
+ type: "directory",
151
+ source: { source: "directory", path: marketplaceRoot(home) },
152
+ installLocation: marketplaceRoot(home),
153
+ description: "MemoraX Code local integration marketplace",
154
+ lastUpdated: new Date().toISOString(),
155
+ autoUpdate: false,
156
+ };
157
+ } else {
158
+ delete known[MARKETPLACE_NAME];
159
+ }
160
+ await writeJsonFile(path, known);
161
+ }
162
+ async function updateSettings(home, mutate) {
163
+ const path = codeBuddySettingsPath(home);
164
+ await updateJsonRecord(path, mutate);
165
+ }
166
+
167
+ async function updateRegistry(home, mutate) {
168
+ const path = installedRegistryPath(home);
169
+ await updateJsonRecord(path, (value) => {
170
+ value.version = 2;
171
+ value.plugins = recordValue(value.plugins);
172
+ mutate(value.plugins);
173
+ });
174
+ }
175
+
176
+ async function updateJsonRecord(path, mutate) {
177
+ const lockPath = `${path}.lock`;
178
+ await mkdir(dirname(path), { recursive: true });
179
+ let handle;
180
+ for (let attempt = 0; attempt < 100; attempt += 1) {
181
+ try {
182
+ handle = await import("node:fs/promises").then(({ open }) => open(lockPath, "wx", 0o600));
183
+ break;
184
+ } catch (error) {
185
+ if (error?.code !== "EEXIST") throw error;
186
+ await new Promise((resolve) => setTimeout(resolve, Math.min(50, 5 + attempt)));
187
+ }
188
+ }
189
+ if (!handle) throw new Error(`timed out acquiring lock: ${lockPath}`);
190
+ try {
191
+ const value = await readJsonRecord(path);
192
+ mutate(value);
193
+ await writeJsonFile(path, value);
194
+ } finally {
195
+ await handle.close();
196
+ await rm(lockPath, { force: true });
197
+ }
198
+ }
199
+ async function readJsonRecord(path) {
200
+ try {
201
+ const value = JSON.parse(await readFile(path, "utf8"));
202
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
203
+ throw new Error(`invalid JSON object: ${path}`);
204
+ } catch (error) {
205
+ if (error?.code === "ENOENT") return {};
206
+ throw error;
207
+ }
208
+ }
209
+ async function writeJsonFile(path, value) {
210
+ await mkdir(dirname(path), { recursive: true });
211
+ let mode = 0o600;
212
+ try { mode = (await stat(path)).mode & 0o777; } catch {}
213
+ const temp = `${path}.tmp-${process.pid}-${Date.now()}`;
214
+ await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { mode });
215
+ await chmod(temp, mode);
216
+ await rename(temp, path);
217
+ }
218
+ async function pathExists(path) { try { await stat(path); return true; } catch { return false; } }
219
+ function recordValue(value) { return value && typeof value === "object" && !Array.isArray(value) ? value : {}; }
220
+ function readPluginVersion() {
221
+ const manifest = JSON.parse(readFileSync(join(ROOT, ".codebuddy-plugin", "plugin.json"), "utf8"));
222
+ if (typeof manifest?.version !== "string" || !manifest.version.trim()) {
223
+ throw new Error("MemoraX Code CodeBuddy plugin manifest has no version.");
224
+ }
225
+ return manifest.version.trim();
226
+ }
227
+ function legacyCodeBuddyInstallPath(home) { return join(home, "plugins", "cache", PLUGIN_NAME, VERSION); }
228
+
229
+ async function materializeCanonicalSkill(destination) {
230
+ const packagedSkill = join(ROOT, "skills", "memorax-code");
231
+ const canonicalSkill = join(ROOT, "..", "memorax-code-codex-adapter", "skills", "memorax-code");
232
+ const source = await pathExists(packagedSkill) ? packagedSkill : canonicalSkill;
233
+ if (!await pathExists(source)) throw new Error(`MemoraX Code canonical skill is unavailable: ${source}`);
234
+ const target = join(destination, "skills", "memorax-code");
235
+ await rm(target, { recursive: true, force: true });
236
+ await mkdir(dirname(target), { recursive: true });
237
+ await cp(source, target, { recursive: true, force: true });
238
+ }
239
+
240
+ async function writePackageMetadata(destination, configuredCommand, codeBuddyHome) {
241
+ const codeBuddyCommand = typeof configuredCommand === "string" && configuredCommand.trim()
242
+ ? configuredCommand.trim()
243
+ : resolveHookCodeBuddyCommand();
244
+ await writeJsonFile(join(destination, ".memorax-code-package.json"), {
245
+ version: 1,
246
+ codeBuddyCommand,
247
+ codeBuddyHome,
248
+ });
249
+ }
250
+
251
+ async function materializeCommonRuntime(destination) {
252
+ const source = join(ROOT, "..", "memorax-code-adapter-common", "src");
253
+ const target = join(destination, "memorax-code-adapter-common", "src");
254
+ await rm(target, { recursive: true, force: true });
255
+ await mkdir(dirname(target), { recursive: true });
256
+ await cp(source, target, { recursive: true, force: true, filter: packageCopyFilter(source) });
257
+ }
258
+
259
+ function packageCopyFilter(root) {
260
+ return (source) => !relative(root, source).split(sep).some((part) => part === "test" || part === "node_modules");
261
+ }
262
+
263
+ function defaultMemoraxCodeHome() {
264
+ return process.env.MEMORAX_CODE_HOME?.trim() || join(homedir(), ".memorax-code");
265
+ }
266
+
267
+ function observationMatches(observation, codeBuddyHome, platform) {
268
+ if (observation?.pluginVersion !== VERSION) return false;
269
+ const left = comparablePath(observation.codeBuddyHome, platform);
270
+ const right = comparablePath(codeBuddyHome, platform);
271
+ return left === right;
272
+ }
273
+
274
+ function comparablePath(value, platform) {
275
+ const normalized = String(value ?? "").replaceAll("\\", "/").replace(/\/+$/, "");
276
+ return platform === "win32" ? normalized.toLowerCase() : normalized;
277
+ }
@@ -0,0 +1,47 @@
1
+ import { readFile, stat, writeFile } from "node:fs/promises";
2
+ import { join, win32 } from "node:path";
3
+
4
+ const REQUIRED_EVENTS = ["SessionStart", "UserPromptSubmit", "Stop"];
5
+ const PORTABLE_COMMAND = 'node "${CODEBUDDY_PLUGIN_ROOT}/hooks/runtime-hook.mjs" turn';
6
+
7
+ export function codeBuddyHookCommand(pluginRoot, platform = process.platform) {
8
+ if (platform !== "win32") return PORTABLE_COMMAND;
9
+ return `node "${win32.join(pluginRoot, "hooks", "runtime-hook.mjs").replaceAll("\\", "/")}" turn`;
10
+ }
11
+
12
+ export async function materializeCodeBuddyHookManifest(pluginRoot, platform = process.platform) {
13
+ if (platform !== "win32") return;
14
+ const path = join(pluginRoot, "hooks", "hooks.json");
15
+ const manifest = JSON.parse(await readFile(path, "utf8"));
16
+ const command = codeBuddyHookCommand(pluginRoot, platform);
17
+ for (const event of REQUIRED_EVENTS) {
18
+ const hooks = commandHooks(manifest, event);
19
+ if (hooks.length === 0) throw new Error(`CodeBuddy Hook manifest is missing ${event}`);
20
+ for (const hook of hooks) hook.command = command;
21
+ }
22
+ await writeFile(path, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
23
+ }
24
+
25
+ export async function codeBuddyHookManifestConfigured(pluginRoot, platform = process.platform) {
26
+ try {
27
+ await stat(join(pluginRoot, "hooks", "runtime-hook.mjs"));
28
+ const manifest = JSON.parse(await readFile(join(pluginRoot, "hooks", "hooks.json"), "utf8"));
29
+ const expected = codeBuddyHookCommand(pluginRoot, platform);
30
+ return REQUIRED_EVENTS.every((event) => {
31
+ const hooks = commandHooks(manifest, event);
32
+ return hooks.length > 0 && hooks.every((hook) => hook.command === expected);
33
+ });
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ function commandHooks(manifest, event) {
40
+ const matchers = manifest?.hooks?.[event];
41
+ if (!Array.isArray(matchers)) return [];
42
+ return matchers.flatMap((matcher) => (
43
+ Array.isArray(matcher?.hooks)
44
+ ? matcher.hooks.filter((hook) => hook?.type === "command" && typeof hook.command === "string")
45
+ : []
46
+ ));
47
+ }