@kolivri/memoreal-mcp 1.0.2 → 1.1.0

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.
@@ -0,0 +1,945 @@
1
+ #!/usr/bin/env node
2
+ import { fileURLToPath } from "node:url"
3
+ import path from "node:path"
4
+ import fs from "node:fs"
5
+ import os from "node:os"
6
+ import crypto from "node:crypto"
7
+
8
+ export function deriveNamespaceCrossOs(rawPath = process.cwd()) {
9
+ if (!rawPath) return ""
10
+ let p = String(rawPath).replace(/\\/g, "/")
11
+ p = p
12
+ .replace(/\/\.worktrees(?:\/.*)?$/, "")
13
+ .replace(/\/\.claude\/worktrees(?:\/.*)?$/, "")
14
+ .replace(/\/\.opencode\/worktrees(?:\/.*)?$/, "")
15
+ .replace(/\/\.codex\/worktrees(?:\/.*)?$/, "")
16
+ .replace(/\/\.cursor\/worktrees(?:\/.*)?$/, "")
17
+ .replace(/\/\.local\/share\/opencode\/worktree\/[^/]+\/[^/]+(?:\/.*)?$/, "")
18
+ if (p.length > 1 && !/^[a-zA-Z]:\/$/.test(p)) {
19
+ p = p.replace(/\/+$/, "")
20
+ }
21
+ if (/^[a-zA-Z]:/.test(p)) {
22
+ p = p.replace(/^([a-zA-Z]):\/*/, "$1-")
23
+ }
24
+ p = p.replace(/[:/]/g, "-")
25
+ p = p.replace(/^([a-zA-Z])-+(?=[^/-])/, "$1-")
26
+ return p
27
+ }
28
+
29
+ export function readSmallText(filePath, maxBytes = 65536) {
30
+ try {
31
+ const stat = fs.lstatSync(filePath, { throwIfNoEntry: false })
32
+ if (!stat || stat.isSymbolicLink() || stat.isDirectory()) return ""
33
+ const fd = fs.openSync(filePath, "r")
34
+ try {
35
+ const bytesToRead = Math.min(stat.size, maxBytes)
36
+ const buf = Buffer.alloc(bytesToRead)
37
+ const bytesRead = fs.readSync(fd, buf, 0, bytesToRead, 0)
38
+ return buf.toString("utf8", 0, bytesRead)
39
+ } finally {
40
+ fs.closeSync(fd)
41
+ }
42
+ } catch {
43
+ return ""
44
+ }
45
+ }
46
+
47
+ function resolveClientVersion() {
48
+ try {
49
+ const pkgPath = fileURLToPath(new URL("../package.json", import.meta.url))
50
+ const raw = readSmallText(pkgPath)
51
+ if (raw) {
52
+ const parsed = JSON.parse(raw)
53
+ if (parsed?.version) return String(parsed.version)
54
+ }
55
+ } catch {}
56
+ return "1.1.0"
57
+ }
58
+
59
+ export const MEMOREAL_CLIENT_VERSION = resolveClientVersion()
60
+
61
+ export function sanitizeLogicalNamespace(raw) {
62
+ if (!raw || typeof raw !== "string") return ""
63
+ let str = raw.trim()
64
+ if (/^wing:[a-z0-9_-]+$/.test(str)) {
65
+ return str
66
+ }
67
+ str = str.replace(/^(?:[:/]*org:)+/i, "")
68
+ str = str.replace(/^@([^/]+)\/(.+)$/, "$1-$2")
69
+ str = str.replace(/[^A-Za-z0-9._-]+/g, "-")
70
+ str = str.replace(/^[-.]+|[-.]+$/g, "")
71
+ str = str.toLowerCase()
72
+ if (str.length > 128) {
73
+ const hash = crypto.createHash("sha256").update(str).digest("hex").slice(0, 8)
74
+ str = str.slice(0, 119) + "-" + hash
75
+ }
76
+ return str
77
+ }
78
+
79
+ export const GENERIC_MANIFEST_NAMES = new Set([
80
+ "app",
81
+ "my-app",
82
+ "myapp",
83
+ "vite-project",
84
+ "server",
85
+ "client",
86
+ "api",
87
+ "web",
88
+ "frontend",
89
+ "backend",
90
+ "root",
91
+ "monorepo",
92
+ "workspace",
93
+ "main",
94
+ "__main__",
95
+ "laravel-laravel",
96
+ "laravel/laravel",
97
+ "symfony-skeleton",
98
+ "example",
99
+ "starter",
100
+ "template",
101
+ "demo",
102
+ "sample",
103
+ "test",
104
+ "tests",
105
+ "core",
106
+ "base",
107
+ "src",
108
+ ])
109
+
110
+ function parseJsonc(text) {
111
+ if (!text) return null
112
+ try {
113
+ const stripped = text
114
+ .replace(/\/\*[\s\S]*?\*\//g, "")
115
+ .replace(/(^|[^\\:])\/\/.*$/gm, "$1")
116
+ return JSON.parse(stripped)
117
+ } catch {
118
+ return null
119
+ }
120
+ }
121
+
122
+ export function extractGitRemoteSlug(commonGitDir) {
123
+ if (!commonGitDir) return null
124
+ const configPath = path.join(commonGitDir, "config")
125
+ const content = readSmallText(configPath)
126
+ if (!content) return null
127
+
128
+ const remoteMatch = content.match(/\[remote\s+["']origin["']\]([\s\S]*?)(?:\r?\n\s*\[|$)/i)
129
+ if (!remoteMatch) return null
130
+
131
+ const urlMatch = remoteMatch[1].match(/^\s*url\s*=\s*(.+)$/m)
132
+ if (!urlMatch) return null
133
+
134
+ let rawUrl = urlMatch[1].trim()
135
+ rawUrl = rawUrl.replace(/\.git\/?$/i, "")
136
+ const parts = rawUrl.split(/[/:]/).filter(Boolean)
137
+ if (!parts.length) return null
138
+ const slug = parts[parts.length - 1]
139
+ const sanitized = sanitizeLogicalNamespace(slug)
140
+ return sanitized && !GENERIC_MANIFEST_NAMES.has(sanitized) ? sanitized : null
141
+ }
142
+
143
+ export function extractManifestProjectName(rootDir) {
144
+ if (!rootDir || typeof rootDir !== "string") return null
145
+
146
+ // 1. package.json
147
+ const pkg = parseJsonc(readSmallText(path.join(rootDir, "package.json")))
148
+ if (pkg?.name && typeof pkg.name === "string") return pkg.name
149
+
150
+ // 2. deno.json / deno.jsonc
151
+ for (const f of ["deno.json", "deno.jsonc"]) {
152
+ const d = parseJsonc(readSmallText(path.join(rootDir, f)))
153
+ if (d?.name && typeof d.name === "string") return d.name
154
+ }
155
+
156
+ // 3. jsr.json / jsr.jsonc
157
+ for (const f of ["jsr.json", "jsr.jsonc"]) {
158
+ const j = parseJsonc(readSmallText(path.join(rootDir, f)))
159
+ if (j?.name && typeof j.name === "string") return j.name
160
+ }
161
+
162
+ // 4. Cargo.toml: scoped to [package] line-anchored section
163
+ const cargoText = readSmallText(path.join(rootDir, "Cargo.toml"))
164
+ if (cargoText) {
165
+ const pkgSection = cargoText.match(/\[package\]([\s\S]*?)(?:\r?\n\s*\[|$)/)
166
+ if (pkgSection) {
167
+ const m = pkgSection[1].match(/^\s*name\s*=\s*["']([^"']+)["']/m)
168
+ if (m) return m[1]
169
+ }
170
+ }
171
+
172
+ // 5. pyproject.toml: [project].name, [tool.poetry].name, [tool.flit.metadata].module
173
+ const pyprojText = readSmallText(path.join(rootDir, "pyproject.toml"))
174
+ if (pyprojText) {
175
+ const projSection = pyprojText.match(/\[project\]([\s\S]*?)(?:\r?\n\s*\[|$)/)
176
+ if (projSection) {
177
+ const m = projSection[1].match(/^\s*name\s*=\s*["']([^"']+)["']/m)
178
+ if (m) return m[1]
179
+ }
180
+ const poetrySection = pyprojText.match(/\[tool\.poetry\]([\s\S]*?)(?:\r?\n\s*\[|$)/)
181
+ if (poetrySection) {
182
+ const m = poetrySection[1].match(/^\s*name\s*=\s*["']([^"']+)["']/m)
183
+ if (m) return m[1]
184
+ }
185
+ const flitSection = pyprojText.match(/\[tool\.flit\.metadata\]([\s\S]*?)(?:\r?\n\s*\[|$)/)
186
+ if (flitSection) {
187
+ const m = flitSection[1].match(/^\s*(?:module|name)\s*=\s*["']([^"']+)["']/m)
188
+ if (m) return m[1]
189
+ }
190
+ }
191
+
192
+ // 6. setup.cfg: [metadata].name
193
+ const setupCfg = readSmallText(path.join(rootDir, "setup.cfg"))
194
+ if (setupCfg) {
195
+ const meta = setupCfg.match(/\[metadata\]([\s\S]*?)(?:\r?\n\s*\[|$)/)
196
+ if (meta) {
197
+ const m = meta[1].match(/^\s*name\s*=\s*["']?([^"'#\r\n]+)["']?/m)
198
+ if (m) return m[1].trim()
199
+ }
200
+ }
201
+
202
+ // 7. setup.py: setup(name='...')
203
+ const setupPy = readSmallText(path.join(rootDir, "setup.py"))
204
+ if (setupPy) {
205
+ const m = setupPy.match(/\bsetup\s*\([^)]*?\bname\s*=\s*["']([^"']+)["']/s)
206
+ if (m) return m[1]
207
+ }
208
+
209
+ // 8. go.mod: module <mod> stripping /v2..vN and domain prefix
210
+ const goMod = readSmallText(path.join(rootDir, "go.mod"))
211
+ if (goMod) {
212
+ const m = goMod.match(/^\s*module\s+([^\s\r\n]+)/m)
213
+ if (m) {
214
+ let mod = m[1].trim()
215
+ mod = mod.replace(/\/v\d+$/i, "")
216
+ mod = mod.replace(/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\//, "")
217
+ if (mod) return mod
218
+ }
219
+ }
220
+
221
+ // 9. settings.gradle / settings.gradle.kts: rootProject.name
222
+ for (const f of ["settings.gradle", "settings.gradle.kts"]) {
223
+ const t = readSmallText(path.join(rootDir, f))
224
+ if (t) {
225
+ const m = t.match(/rootProject\.name\s*=\s*['"]([^'"]+)['"]/)
226
+ if (m) return m[1]
227
+ }
228
+ }
229
+
230
+ // 10. build.gradle / build.gradle.kts: applicationId, namespace, archivesBaseName
231
+ for (const f of ["build.gradle", "build.gradle.kts"]) {
232
+ const t = readSmallText(path.join(rootDir, f))
233
+ if (t) {
234
+ const m = t.match(/(?:applicationId|namespace|archivesBaseName)\s*(?:=|\s)\s*['"]([^'"]+)['"]/)
235
+ if (m) return m[1]
236
+ }
237
+ }
238
+
239
+ // 11. pom.xml: <artifactId> after stripping parent/build/dependencies/etc.
240
+ const pomXml = readSmallText(path.join(rootDir, "pom.xml"))
241
+ if (pomXml) {
242
+ let stripped = pomXml.replace(/<!--[\s\S]*?-->/g, "")
243
+ stripped = stripped
244
+ .replace(/<parent>[\s\S]*?<\/parent>/gi, "")
245
+ .replace(/<build>[\s\S]*?<\/build>/gi, "")
246
+ .replace(/<dependencies>[\s\S]*?<\/dependencies>/gi, "")
247
+ .replace(/<dependencyManagement>[\s\S]*?<\/dependencyManagement>/gi, "")
248
+ .replace(/<profiles>[\s\S]*?<\/profiles>/gi, "")
249
+ .replace(/<reporting>[\s\S]*?<\/reporting>/gi, "")
250
+ const m = stripped.match(/<artifactId>\s*([^<\s]+)\s*<\/artifactId>/i)
251
+ if (m) return m[1]
252
+ }
253
+
254
+ // 12. module.yaml: product: ...
255
+ const modYaml = readSmallText(path.join(rootDir, "module.yaml"))
256
+ if (modYaml) {
257
+ const m = modYaml.match(/^\s*product:\s*['"]?([^'"\s\r\n]+)['"]?/m)
258
+ if (m) return m[1]
259
+ }
260
+
261
+ // 13. build.sbt: val root or top-level name :=
262
+ const sbt = readSmallText(path.join(rootDir, "build.sbt"))
263
+ if (sbt) {
264
+ const m = sbt.match(/\bname\s*:=\s*["']([^"']+)["']/)
265
+ if (m) return m[1]
266
+ }
267
+
268
+ // 14. *.slnx / *.sln / *.csproj / *.fsproj / *.vbproj
269
+ try {
270
+ const files = fs.readdirSync(rootDir)
271
+ for (const f of files) {
272
+ if (/\.(csproj|fsproj|vbproj)$/i.test(f)) {
273
+ const proj = readSmallText(path.join(rootDir, f))
274
+ const pMatch = proj.match(/<(?:PackageId|AssemblyName)>\s*([^<\s]+)\s*<\/(?:PackageId|AssemblyName)>/i)
275
+ if (pMatch) return pMatch[1]
276
+ const stem = f.replace(/\.(csproj|fsproj|vbproj)$/i, "")
277
+ if (!/(?:tests?|\.tests?)$/i.test(stem)) return stem
278
+ }
279
+ }
280
+ for (const f of files) {
281
+ if (/\.(slnx|sln)$/i.test(f)) {
282
+ const stem = f.replace(/\.(slnx|sln)$/i.test(f) ? /\.(slnx|sln)$/i : "", "")
283
+ if (!/(?:tests?|\.tests?)$/i.test(stem)) return stem
284
+ }
285
+ }
286
+ } catch {}
287
+
288
+ // 15. CMakeLists.txt: project(...)
289
+ const cmake = readSmallText(path.join(rootDir, "CMakeLists.txt"))
290
+ if (cmake) {
291
+ const m = cmake.match(/\bproject\s*\(\s*["']?([A-Za-z0-9_.-]+)/i)
292
+ if (m) return m[1]
293
+ }
294
+
295
+ // 16. meson.build: project('name')
296
+ const meson = readSmallText(path.join(rootDir, "meson.build"))
297
+ if (meson) {
298
+ const m = meson.match(/\bproject\s*\(\s*['"]([^'"]+)['"]/)
299
+ if (m) return m[1]
300
+ }
301
+
302
+ // 17. vcpkg.json
303
+ const vcpkg = parseJsonc(readSmallText(path.join(rootDir, "vcpkg.json")))
304
+ if (vcpkg?.name && typeof vcpkg.name === "string") return vcpkg.name
305
+
306
+ // 18. conanfile.py: name = '...'
307
+ const conan = readSmallText(path.join(rootDir, "conanfile.py"))
308
+ if (conan) {
309
+ const m = conan.match(/^\s*name\s*=\s*['"]([^'"]+)['"]/m)
310
+ if (m) return m[1]
311
+ }
312
+
313
+ // 19. MODULE.bazel / WORKSPACE
314
+ const bazelMod = readSmallText(path.join(rootDir, "MODULE.bazel"))
315
+ if (bazelMod) {
316
+ const m = bazelMod.match(/\bmodule\s*\(\s*name\s*=\s*["']([^"']+)["']/)
317
+ if (m) return m[1]
318
+ }
319
+ for (const wf of ["WORKSPACE.bazel", "WORKSPACE"]) {
320
+ const w = readSmallText(path.join(rootDir, wf))
321
+ if (w) {
322
+ const m = w.match(/\bworkspace\s*\(\s*name\s*=\s*["']([^"']+)["']/)
323
+ if (m) return m[1]
324
+ }
325
+ }
326
+
327
+ // 20. xmake.lua: set_project
328
+ const xmake = readSmallText(path.join(rootDir, "xmake.lua"))
329
+ if (xmake) {
330
+ const m = xmake.match(/\bset_project\s*(?:\(\s*["']([^"']+)["']\s*\)|["']([^"']+)["'])/)
331
+ if (m) return m[1] || m[2]
332
+ }
333
+
334
+ // 21. Package.swift: anchored Package(name:) with comments stripped
335
+ const swiftPkg = readSmallText(path.join(rootDir, "Package.swift"))
336
+ if (swiftPkg) {
337
+ const stripped = swiftPkg
338
+ .replace(/\/\*[\s\S]*?\*\//g, "")
339
+ .replace(/(^|[^\\:])\/\/.*$/gm, "$1")
340
+ const m = stripped.match(/\bPackage\s*\([\s\S]*?\bname\s*:\s*["']([^"']+)["']/)
341
+ if (m) return m[1]
342
+ }
343
+
344
+ // 22. *.podspec
345
+ try {
346
+ const files = fs.readdirSync(rootDir)
347
+ for (const f of files) {
348
+ if (/\.podspec$/i.test(f)) {
349
+ const pod = readSmallText(path.join(rootDir, f))
350
+ const m = pod.match(/\.name\s*=\s*['"]([^'"]+)['"]/)
351
+ if (m) return m[1]
352
+ return f.replace(/\.podspec$/i, "")
353
+ }
354
+ }
355
+ } catch {}
356
+
357
+ // 23. pubspec.yaml: col-0 ^name:
358
+ const pubspec = readSmallText(path.join(rootDir, "pubspec.yaml"))
359
+ if (pubspec) {
360
+ const m = pubspec.match(/^name:\s*['"]?([A-Za-z0-9_-]+)['"]?/m)
361
+ if (m) return m[1]
362
+ }
363
+
364
+ // 24. composer.json
365
+ const composer = parseJsonc(readSmallText(path.join(rootDir, "composer.json")))
366
+ if (composer?.name && typeof composer.name === "string") return composer.name
367
+
368
+ // 25. *.gemspec & Rails config/application.rb
369
+ try {
370
+ const files = fs.readdirSync(rootDir)
371
+ for (const f of files) {
372
+ if (/\.gemspec$/i.test(f)) {
373
+ const gem = readSmallText(path.join(rootDir, f))
374
+ const m = gem.match(/\.name\s*=\s*['"]([^'"]+)['"]/)
375
+ if (m) return m[1]
376
+ }
377
+ }
378
+ } catch {}
379
+ const railsApp = readSmallText(path.join(rootDir, "config", "application.rb"))
380
+ if (railsApp) {
381
+ const m = railsApp.match(/^\s*module\s+([A-Za-z0-9_]+)/m)
382
+ if (m) return m[1]
383
+ }
384
+
385
+ // 26. mix.exs: app: :atom or defmodule X.MixProject
386
+ const mix = readSmallText(path.join(rootDir, "mix.exs"))
387
+ if (mix) {
388
+ const mApp = mix.match(/\bapp:\s*:([a-zA-Z0-9_]+)/)
389
+ if (mApp) return mApp[1]
390
+ const mMod = mix.match(/\bdefmodule\s+([A-Za-z0-9_]+)\.MixProject/)
391
+ if (mMod) return mMod[1]
392
+ }
393
+
394
+ // 27. src/*.app.src & rebar.config
395
+ try {
396
+ const srcDir = path.join(rootDir, "src")
397
+ if (fs.existsSync(srcDir)) {
398
+ const srcFiles = fs.readdirSync(srcDir)
399
+ for (const sf of srcFiles) {
400
+ if (/\.app\.src$/i.test(sf)) {
401
+ const appSrc = readSmallText(path.join(srcDir, sf))
402
+ const m = appSrc.match(/\{\s*application\s*,\s*([a-zA-Z0-9_]+)/)
403
+ if (m) return m[1]
404
+ }
405
+ }
406
+ }
407
+ } catch {}
408
+
409
+ // 28. *.cabal & package.yaml
410
+ const hpack = readSmallText(path.join(rootDir, "package.yaml"))
411
+ if (hpack) {
412
+ const m = hpack.match(/^name:\s*['"]?([A-Za-z0-9_-]+)['"]?/m)
413
+ if (m) return m[1]
414
+ }
415
+ try {
416
+ const files = fs.readdirSync(rootDir)
417
+ for (const f of files) {
418
+ if (/\.cabal$/i.test(f)) {
419
+ const cabal = readSmallText(path.join(rootDir, f))
420
+ const m = cabal.match(/^name:\s*([^\s\r\n]+)/im)
421
+ if (m) return m[1]
422
+ return f.replace(/\.cabal$/i, "")
423
+ }
424
+ }
425
+ } catch {}
426
+
427
+ // 29. dune-project & *.opam
428
+ const dune = readSmallText(path.join(rootDir, "dune-project"))
429
+ if (dune) {
430
+ const m = dune.match(/\(name\s+([^\s\)]+)\)/)
431
+ if (m) return m[1]
432
+ }
433
+ try {
434
+ const files = fs.readdirSync(rootDir)
435
+ for (const f of files) {
436
+ if (/\.opam$/i.test(f)) {
437
+ const opam = readSmallText(path.join(rootDir, f))
438
+ const m = opam.match(/^name:\s*["']([^"']+)["']/m)
439
+ if (m) return m[1]
440
+ return f.replace(/\.opam$/i, "")
441
+ }
442
+ }
443
+ } catch {}
444
+
445
+ // 30. project.clj & deps.edn
446
+ const clj = readSmallText(path.join(rootDir, "project.clj"))
447
+ if (clj) {
448
+ const m = clj.match(/\(\s*defproject\s+([^\s]+)/)
449
+ if (m) return m[1]
450
+ }
451
+
452
+ // 31. build.zig.zon: before .dependencies supporting .name = "pkg" / .pkg / .@"pkg"
453
+ const zigZon = readSmallText(path.join(rootDir, "build.zig.zon"))
454
+ if (zigZon) {
455
+ const beforeDeps = zigZon.split(/\.dependencies\s*=/)[0]
456
+ const m = beforeDeps.match(/\.name\s*=\s*(?:\.@["']([^"']+)["']|@["']([^"']+)["']|["']([^"']+)["']|\.([a-zA-Z0-9_-]+))/)
457
+ if (m) return m[1] || m[2] || m[3] || m[4]
458
+ }
459
+
460
+ // 32. Nim, Julia, R, Lua, Perl, Gleam, Crystal, V, D, Elm, Helm, Skaffold, Ansible
461
+ try {
462
+ const files = fs.readdirSync(rootDir)
463
+ for (const f of files) {
464
+ if (/\.nimble$/i.test(f)) return f.replace(/\.nimble$/i, "")
465
+ if (/\.rockspec$/i.test(f)) {
466
+ const rock = readSmallText(path.join(rootDir, f))
467
+ const m = rock.match(/\bpackage\s*=\s*["']([^"']+)["']/)
468
+ if (m) return m[1]
469
+ }
470
+ }
471
+ } catch {}
472
+
473
+ for (const jf of ["Project.toml", "JuliaProject.toml"]) {
474
+ const jt = readSmallText(path.join(rootDir, jf))
475
+ if (jt) {
476
+ const rootSection = jt.split(/\r?\n\[/)[0]
477
+ const m = rootSection.match(/^\s*name\s*=\s*["']([^"']+)["']/m)
478
+ if (m) return m[1]
479
+ }
480
+ }
481
+
482
+ const desc = readSmallText(path.join(rootDir, "DESCRIPTION"))
483
+ if (desc && /(?:Version|Title):/i.test(desc)) {
484
+ const m = desc.match(/^Package:\s*([^\s\r\n]+)/im)
485
+ if (m) return m[1]
486
+ }
487
+
488
+ const perlMeta = parseJsonc(readSmallText(path.join(rootDir, "META.json")))
489
+ if (perlMeta?.name && typeof perlMeta.name === "string") return perlMeta.name
490
+
491
+ const distIni = readSmallText(path.join(rootDir, "dist.ini"))
492
+ if (distIni) {
493
+ const m = distIni.match(/^\s*name\s*=\s*([^\s\r\n]+)/m)
494
+ if (m) return m[1]
495
+ }
496
+
497
+ const makefilePl = readSmallText(path.join(rootDir, "Makefile.PL"))
498
+ if (makefilePl) {
499
+ const m = makefilePl.match(/NAME\s*=>\s*['"]([^'"]+)['"]/)
500
+ if (m) return m[1]
501
+ }
502
+
503
+ const gleam = readSmallText(path.join(rootDir, "gleam.toml"))
504
+ if (gleam) {
505
+ const m = gleam.match(/^\s*name\s*=\s*["']([^"']+)["']/m)
506
+ if (m) return m[1]
507
+ }
508
+
509
+ const shard = readSmallText(path.join(rootDir, "shard.yml"))
510
+ if (shard) {
511
+ const m = shard.match(/^name:\s*['"]?([A-Za-z0-9_-]+)['"]?/m)
512
+ if (m) return m[1]
513
+ }
514
+
515
+ const vmod = readSmallText(path.join(rootDir, "v.mod"))
516
+ if (vmod) {
517
+ const m = vmod.match(/\bname:\s*['"]([^'"]+)["']/)
518
+ if (m) return m[1]
519
+ }
520
+
521
+ const dub = parseJsonc(readSmallText(path.join(rootDir, "dub.json")))
522
+ if (dub?.name && typeof dub.name === "string") return dub.name
523
+
524
+ const elm = parseJsonc(readSmallText(path.join(rootDir, "elm.json")))
525
+ if (elm?.name && typeof elm.name === "string") return elm.name
526
+
527
+ const chart = readSmallText(path.join(rootDir, "Chart.yaml"))
528
+ if (chart) {
529
+ const m = chart.match(/^name:\s*['"]?([A-Za-z0-9_-]+)['"]?/m)
530
+ if (m) return m[1]
531
+ }
532
+
533
+ const skaffold = readSmallText(path.join(rootDir, "skaffold.yaml"))
534
+ if (skaffold) {
535
+ const m = skaffold.match(/^\s*name:\s*['"]?([A-Za-z0-9_-]+)['"]?/m)
536
+ if (m) return m[1]
537
+ }
538
+
539
+ const galaxy = readSmallText(path.join(rootDir, "galaxy.yml"))
540
+ if (galaxy) {
541
+ const m = galaxy.match(/^name:\s*['"]?([A-Za-z0-9_-]+)['"]?/m)
542
+ if (m) return m[1]
543
+ }
544
+
545
+ return null
546
+ }
547
+
548
+ const MONOREPO_ROOT_FILES = [
549
+ "pnpm-workspace.yaml",
550
+ "nx.json",
551
+ "turbo.json",
552
+ "lerna.json",
553
+ "rush.json",
554
+ "go.work",
555
+ "settings.gradle",
556
+ "settings.gradle.kts",
557
+ "cabal.project",
558
+ "stack.yaml",
559
+ "MODULE.bazel",
560
+ "pants.toml",
561
+ ]
562
+
563
+ function hasMonorepoWorkspaceMarker(dir) {
564
+ for (const f of MONOREPO_ROOT_FILES) {
565
+ if (fs.existsSync(path.join(dir, f))) return true
566
+ }
567
+ if (fs.existsSync(path.join(dir, ".moon", "workspace.yml"))) return true
568
+ const cargoText = readSmallText(path.join(dir, "Cargo.toml"))
569
+ if (cargoText && /\[workspace\]/.test(cargoText)) return true
570
+ try {
571
+ const files = fs.readdirSync(dir)
572
+ if (files.some((f) => /\.(slnx|sln)$/i.test(f))) return true
573
+ } catch {}
574
+ return false
575
+ }
576
+
577
+ const BUILD_ROOT_MARKERS = [
578
+ "Makefile",
579
+ "GNUmakefile",
580
+ "BSDmakefile",
581
+ "Justfile",
582
+ "Taskfile.yml",
583
+ "Taskfile.yaml",
584
+ "Dockerfile",
585
+ "docker-compose.yml",
586
+ "docker-compose.yaml",
587
+ "compose.yml",
588
+ "compose.yaml",
589
+ "Vagrantfile",
590
+ "Procfile",
591
+ "compile_commands.json",
592
+ ]
593
+
594
+ const LAYOUT_SUBDIRS = new Set([
595
+ "src",
596
+ "lib",
597
+ "include",
598
+ "cmd",
599
+ "internal",
600
+ "pkg",
601
+ "app",
602
+ "crates",
603
+ "packages",
604
+ "test",
605
+ "tests",
606
+ "bin",
607
+ ])
608
+
609
+ const CODE_FILE_EXTENSIONS = /\.(js|mjs|cjs|jsx|ts|mts|cts|tsx|rs|py|go|java|kt|kts|c|h|cc|cpp|hpp|cxx|cs|rb|php|swift|scala|dart|ex|exs|lua|sh|bash|zsh|sql|zig|nim|hs|ml|clj|r|jl|gleam|v|d|elm|proto|graphql)$/i
610
+
611
+ function getStopDirs(env = process.env) {
612
+ const home = env?.MEMOREAL_HOME || env?.HOME || env?.USERPROFILE || os.homedir()
613
+ const dirs = [home, os.homedir(), os.tmpdir(), "/tmp", "/var/tmp", "/private/tmp"]
614
+ const res = new Set()
615
+ for (const d of dirs) {
616
+ if (!d) continue
617
+ const p = path.resolve(d)
618
+ res.add(p)
619
+ try {
620
+ res.add(fs.realpathSync(p))
621
+ } catch {}
622
+ }
623
+ return res
624
+ }
625
+
626
+ function hasBuildRootMarker(dir) {
627
+ for (const m of BUILD_ROOT_MARKERS) {
628
+ if (fs.existsSync(path.join(dir, m))) return true
629
+ }
630
+ return false
631
+ }
632
+
633
+ function hasChildLayoutDirWithFiles(dir) {
634
+ for (const sub of ["src", "lib", "include", "cmd", "internal"]) {
635
+ const subPath = path.join(dir, sub)
636
+ if (fs.existsSync(subPath)) {
637
+ try {
638
+ if (fs.readdirSync(subPath).length > 0) return true
639
+ } catch {}
640
+ }
641
+ }
642
+ return false
643
+ }
644
+
645
+ function findNearestCodeRoot(resolvedStart, stopDirs) {
646
+ // Step A: If resolvedStart itself has a BUILD_ROOT_MARKERS file OR has a child layout directory containing entries
647
+ if (hasBuildRootMarker(resolvedStart) || hasChildLayoutDirWithFiles(resolvedStart)) {
648
+ return resolvedStart
649
+ }
650
+
651
+ // Step B: Walk upward looking for BUILD_ROOT_MARKERS or exiting a LAYOUT_SUBDIRS chain
652
+ let curr = path.dirname(resolvedStart)
653
+ while (curr && curr !== path.dirname(curr) && !stopDirs.has(curr)) {
654
+ if (hasBuildRootMarker(curr)) {
655
+ return curr
656
+ }
657
+
658
+ const rel = path.relative(curr, resolvedStart)
659
+ const firstSeg = rel.split(path.sep)[0]
660
+ if (LAYOUT_SUBDIRS.has(firstSeg.toLowerCase())) {
661
+ const currBase = path.basename(curr).toLowerCase()
662
+ if (!LAYOUT_SUBDIRS.has(currBase)) {
663
+ return curr
664
+ }
665
+ }
666
+
667
+ curr = path.dirname(curr)
668
+ }
669
+
670
+ // Step C: If neither Step A nor Step B found a root, and resolvedStart itself contains source code files
671
+ try {
672
+ const entries = fs.readdirSync(resolvedStart)
673
+ if (entries.some((e) => CODE_FILE_EXTENSIONS.test(e))) {
674
+ return resolvedStart
675
+ }
676
+ } catch {}
677
+
678
+ return null
679
+ }
680
+
681
+ export function resolveCanonicalProjectRoot(startDir = process.cwd(), env = process.env) {
682
+ if (!startDir) startDir = process.cwd()
683
+ let p = String(startDir).replace(/\\/g, "/")
684
+ p = p
685
+ .replace(/\/\.worktrees(?:\/.*)?$/, "")
686
+ .replace(/\/\.claude\/worktrees(?:\/.*)?$/, "")
687
+ .replace(/\/\.opencode\/worktrees(?:\/.*)?$/, "")
688
+ .replace(/\/\.codex\/worktrees(?:\/.*)?$/, "")
689
+ .replace(/\/\.cursor\/worktrees(?:\/.*)?$/, "")
690
+
691
+ if (!fs.existsSync(p)) {
692
+ p = p.replace(/\/\.local\/share\/opencode\/worktree\/[^/]+\/[^/]+(?:\/.*)?$/, "")
693
+ return {
694
+ canonicalRoot: p,
695
+ isCodeProject: false,
696
+ gitDir: null,
697
+ commonGitDir: null,
698
+ }
699
+ }
700
+
701
+ const resolvedStart = path.resolve(p)
702
+ const stopDirs = getStopDirs(env)
703
+
704
+ const normResolved = resolvedStart.replace(/\\/g, "/")
705
+ const opencodeWtMatch = normResolved.match(/^([\s\S]*?\/\.local\/share\/opencode\/worktree\/[^/]+)\/([^/]+)(?:\/.*)?$/)
706
+ if (opencodeWtMatch) {
707
+ const wtParent = path.resolve(opencodeWtMatch[1])
708
+ stopDirs.add(wtParent)
709
+ try {
710
+ stopDirs.add(fs.realpathSync(wtParent))
711
+ } catch {}
712
+ }
713
+
714
+ let curr = resolvedStart
715
+ let gitDir = null
716
+ let commonGitDir = null
717
+ let gitRoot = null
718
+ let outermostMonorepoRoot = null
719
+ let manifestAncestorRoot = null
720
+
721
+ while (true) {
722
+ if (stopDirs.has(curr)) break
723
+
724
+ // 1. Check VCS roots (.git, .hg, .svn, .jj)
725
+ const gitPath = path.join(curr, ".git")
726
+ if (!gitRoot && fs.existsSync(gitPath)) {
727
+ try {
728
+ const stat = fs.lstatSync(gitPath)
729
+ if (stat.isDirectory()) {
730
+ gitDir = gitPath
731
+ commonGitDir = gitPath
732
+ gitRoot = curr
733
+ } else if (stat.isFile()) {
734
+ const content = readSmallText(gitPath)
735
+ const m = content.match(/^\s*gitdir:\s*(.+)$/m)
736
+ if (m) {
737
+ const targetGitDir = path.resolve(curr, m[1].trim())
738
+ gitDir = targetGitDir
739
+ const commondirFile = path.join(targetGitDir, "commondir")
740
+ if (fs.existsSync(commondirFile)) {
741
+ const commondirContent = readSmallText(commondirFile).trim()
742
+ if (commondirContent) {
743
+ commonGitDir = path.resolve(targetGitDir, commondirContent)
744
+ gitRoot = path.dirname(commonGitDir)
745
+ }
746
+ }
747
+ if (!gitRoot) {
748
+ const normTarget = targetGitDir.replace(/\\/g, "/")
749
+ if (normTarget.includes("/.git/worktrees/")) {
750
+ commonGitDir = path.resolve(targetGitDir, "../..")
751
+ gitRoot = path.dirname(commonGitDir)
752
+ } else {
753
+ commonGitDir = targetGitDir
754
+ gitRoot = curr
755
+ }
756
+ }
757
+ }
758
+ }
759
+ } catch {}
760
+ } else if (!gitRoot) {
761
+ for (const vcs of [".hg", ".svn", ".jj"]) {
762
+ if (fs.existsSync(path.join(curr, vcs))) {
763
+ gitRoot = curr
764
+ break
765
+ }
766
+ }
767
+ }
768
+
769
+ // 2. Check monorepo workspace markers
770
+ if (hasMonorepoWorkspaceMarker(curr)) {
771
+ outermostMonorepoRoot = curr
772
+ }
773
+
774
+ // 3. Check manifest or .memoreal/.memoria-namespace file
775
+ const hasManifest =
776
+ Boolean(extractManifestProjectName(curr)) ||
777
+ fs.existsSync(path.join(curr, ".memoreal-namespace")) ||
778
+ fs.existsSync(path.join(curr, ".memoria-namespace"))
779
+ if (hasManifest) {
780
+ manifestAncestorRoot = curr
781
+ }
782
+
783
+ const parent = path.dirname(curr)
784
+ if (!parent || parent === curr) break
785
+ curr = parent
786
+ }
787
+
788
+ // When gitRoot resolved via commondir outside ancestors, inspect gitRoot for monorepo roots
789
+ if (gitRoot && fs.existsSync(gitRoot)) {
790
+ let checkDir = gitRoot
791
+ while (true) {
792
+ if (stopDirs.has(checkDir)) break
793
+ if (hasMonorepoWorkspaceMarker(checkDir)) {
794
+ outermostMonorepoRoot = checkDir
795
+ }
796
+ const parent = path.dirname(checkDir)
797
+ if (!parent || parent === checkDir) break
798
+ checkDir = parent
799
+ }
800
+ }
801
+
802
+ const nearestCodeRoot = findNearestCodeRoot(resolvedStart, stopDirs)
803
+ const canonicalRoot = outermostMonorepoRoot || gitRoot || manifestAncestorRoot || nearestCodeRoot || resolvedStart
804
+ const isCodeProject = Boolean(outermostMonorepoRoot || gitRoot || manifestAncestorRoot || nearestCodeRoot)
805
+
806
+ return {
807
+ canonicalRoot,
808
+ isCodeProject,
809
+ gitDir,
810
+ commonGitDir,
811
+ }
812
+ }
813
+
814
+ export function resolveProjectNamespaceInfo(rawPath = process.cwd(), explicitNamespace, env = process.env) {
815
+ const rootInfo = resolveCanonicalProjectRoot(rawPath, env)
816
+ const canonicalRoot = rootInfo.canonicalRoot
817
+ const isCodeProject = rootInfo.isCodeProject
818
+ const legacyNamespace = isCodeProject ? deriveNamespaceCrossOs(canonicalRoot) : null
819
+
820
+ // 1. Explicit namespace
821
+ if (explicitNamespace && typeof explicitNamespace === "string" && explicitNamespace.trim()) {
822
+ const ns = sanitizeLogicalNamespace(explicitNamespace)
823
+ return {
824
+ namespace: ns,
825
+ legacyNamespace: isCodeProject ? legacyNamespace : null,
826
+ isCodeProject,
827
+ canonicalRoot,
828
+ source: "explicit",
829
+ clientVersion: MEMOREAL_CLIENT_VERSION,
830
+ }
831
+ }
832
+
833
+ // 2. .memoreal-namespace or .memoria-namespace file
834
+ for (const checkDir of [canonicalRoot, rawPath]) {
835
+ if (checkDir && fs.existsSync(checkDir)) {
836
+ for (const dotName of [".memoreal-namespace", ".memoria-namespace"]) {
837
+ const dotFile = path.join(checkDir, dotName)
838
+ const dotContent = readSmallText(dotFile).trim()
839
+ if (dotContent) {
840
+ const cleanContent = dotContent.replace(/^(?:[:/]*org:)+/i, "").trim()
841
+ const ns = sanitizeLogicalNamespace(cleanContent)
842
+ if (ns) {
843
+ return {
844
+ namespace: ns,
845
+ legacyNamespace: isCodeProject ? legacyNamespace : null,
846
+ isCodeProject: isCodeProject ? true : false,
847
+ canonicalRoot,
848
+ source: "file",
849
+ clientVersion: MEMOREAL_CLIENT_VERSION,
850
+ }
851
+ }
852
+ }
853
+ }
854
+ }
855
+ }
856
+
857
+ // 3. Environment variable MEMOREAL_NAMESPACE or MEMORIA_NAMESPACE
858
+ const envVal = env?.MEMOREAL_NAMESPACE || env?.MEMORIA_NAMESPACE
859
+ if (envVal && typeof envVal === "string" && envVal.trim() && envVal.trim() !== "default") {
860
+ const ns = sanitizeLogicalNamespace(envVal)
861
+ return {
862
+ namespace: ns,
863
+ legacyNamespace: isCodeProject ? legacyNamespace : null,
864
+ isCodeProject,
865
+ canonicalRoot,
866
+ source: "env",
867
+ clientVersion: MEMOREAL_CLIENT_VERSION,
868
+ }
869
+ }
870
+
871
+ // 4. Non-generic manifest name
872
+ if (fs.existsSync(canonicalRoot)) {
873
+ const manifestRaw =
874
+ extractManifestProjectName(canonicalRoot) ||
875
+ (canonicalRoot !== rawPath && fs.existsSync(rawPath) ? extractManifestProjectName(rawPath) : null)
876
+ if (manifestRaw) {
877
+ const sanitized = sanitizeLogicalNamespace(manifestRaw)
878
+ if (sanitized && !GENERIC_MANIFEST_NAMES.has(sanitized)) {
879
+ return {
880
+ namespace: sanitized,
881
+ legacyNamespace,
882
+ isCodeProject: true,
883
+ canonicalRoot,
884
+ source: "manifest",
885
+ clientVersion: MEMOREAL_CLIENT_VERSION,
886
+ }
887
+ }
888
+ }
889
+ }
890
+
891
+ // 5. Git remote origin slug
892
+ if (rootInfo.commonGitDir) {
893
+ const remoteSlug = extractGitRemoteSlug(rootInfo.commonGitDir)
894
+ if (remoteSlug && !GENERIC_MANIFEST_NAMES.has(remoteSlug)) {
895
+ return {
896
+ namespace: remoteSlug,
897
+ legacyNamespace,
898
+ isCodeProject: true,
899
+ canonicalRoot,
900
+ source: "git-remote",
901
+ clientVersion: MEMOREAL_CLIENT_VERSION,
902
+ }
903
+ }
904
+ }
905
+
906
+ // 6. Directory basename directly as namespace
907
+ if (isCodeProject && fs.existsSync(canonicalRoot)) {
908
+ const baseSlug = sanitizeLogicalNamespace(path.basename(canonicalRoot))
909
+ if (baseSlug) {
910
+ return {
911
+ namespace: baseSlug,
912
+ legacyNamespace,
913
+ isCodeProject: true,
914
+ canonicalRoot,
915
+ source: "repo-dir",
916
+ clientVersion: MEMOREAL_CLIENT_VERSION,
917
+ }
918
+ }
919
+ }
920
+
921
+ // 7. Fallback to path string
922
+ const pathNs = deriveNamespaceCrossOs(canonicalRoot)
923
+ return {
924
+ namespace: pathNs,
925
+ legacyNamespace: null,
926
+ isCodeProject: false,
927
+ canonicalRoot,
928
+ source: "path",
929
+ clientVersion: MEMOREAL_CLIENT_VERSION,
930
+ }
931
+ }
932
+
933
+ const isDirectRun =
934
+ process.argv[1] &&
935
+ (process.argv[1] === fileURLToPath(import.meta.url) ||
936
+ path.basename(process.argv[1]).startsWith("memoreal-ns") ||
937
+ path.basename(process.argv[1]).startsWith("memoria-ns"))
938
+
939
+ if (isDirectRun) {
940
+ const args = process.argv.slice(2)
941
+ const isJson = args.includes("--json")
942
+ const pathArg = args.find((a) => a !== "--json") || process.cwd()
943
+ const info = resolveProjectNamespaceInfo(pathArg)
944
+ process.stdout.write(isJson ? JSON.stringify(info) : info.namespace)
945
+ }