nexus-agents 4.14.1 → 4.14.3
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/dist/{child-mcp-config-E5YGOYIM.js → child-mcp-config-APH7KTWD.js} +5 -5
- package/dist/{chunk-3U3AAMAU.js → chunk-25ZTN5RI.js} +2 -2
- package/dist/{chunk-KQU3HO7T.js → chunk-3FRBJFOX.js} +2 -2
- package/dist/{chunk-45X7AGDF.js → chunk-5DT2LK7C.js} +6 -6
- package/dist/{chunk-RGX43IEW.js → chunk-5WDKJA6B.js} +2 -2
- package/dist/{chunk-SMPLE7KA.js → chunk-6DPOX5GU.js} +3 -3
- package/dist/{chunk-6IDZUUC5.js → chunk-75J5CYUV.js} +4 -4
- package/dist/{chunk-7ERIPG4P.js → chunk-7K4UQJD3.js} +2 -2
- package/dist/{chunk-OC5EBGLD.js → chunk-7PCOAMGG.js} +2 -2
- package/dist/{chunk-CEHYUQTT.js → chunk-7RRQSUX4.js} +4 -4
- package/dist/{chunk-HW3BCQKG.js → chunk-BI6L5HAS.js} +2 -2
- package/dist/{chunk-TYNKSYWN.js → chunk-BRPWBUSX.js} +6 -6
- package/dist/{chunk-6MSKPFFM.js → chunk-BV4L3SWR.js} +7 -7
- package/dist/{chunk-XSOMMTPM.js → chunk-CBFZSAUL.js} +4 -4
- package/dist/{chunk-XHDAHIAJ.js → chunk-CD24GOBY.js} +2 -2
- package/dist/{chunk-LRUPAIVW.js → chunk-FEC3PFSO.js} +2 -2
- package/dist/{chunk-IMI6LRZ2.js → chunk-FLX3LARU.js} +2 -2
- package/dist/{chunk-R4TX27OZ.js → chunk-FZ7ACQTB.js} +2 -2
- package/dist/{chunk-M5KWBRUY.js → chunk-HHHB3R7L.js} +2 -2
- package/dist/{chunk-2HUC6NZN.js → chunk-HHLCAWAV.js} +2 -2
- package/dist/{chunk-HGO7LVRL.js → chunk-JGQ3YQP5.js} +4 -4
- package/dist/{chunk-SJMQFZCV.js → chunk-JUZRCQJI.js} +9 -9
- package/dist/{chunk-XIIUIBSX.js → chunk-KGFFEQTN.js} +2 -2
- package/dist/{chunk-DJ2NGRHS.js → chunk-MVLURKBG.js} +20 -10
- package/dist/chunk-MVLURKBG.js.map +1 -0
- package/dist/{chunk-OQLFRJCW.js → chunk-NBMWONHE.js} +53 -53
- package/dist/chunk-NBMWONHE.js.map +1 -0
- package/dist/{chunk-ULAF5ULM.js → chunk-QE3FY3DG.js} +10 -10
- package/dist/{chunk-SNJNRDKZ.js → chunk-RQV5ZUXT.js} +2 -2
- package/dist/{chunk-LVA53Q4Y.js → chunk-TCKP3H54.js} +2 -2
- package/dist/{chunk-KNDUA6HH.js → chunk-UCVDEZGK.js} +2 -2
- package/dist/chunk-VJJMHVLJ.js +1240 -0
- package/dist/chunk-VJJMHVLJ.js.map +1 -0
- package/dist/{chunk-T25FZOJ3.js → chunk-VP7KIRQQ.js} +6 -6
- package/dist/{chunk-WPLXWTUK.js → chunk-W4Q5NZYZ.js} +5 -3
- package/dist/chunk-W4Q5NZYZ.js.map +1 -0
- package/dist/{chunk-PWUPYWJE.js → chunk-WJA3TLFH.js} +2 -2
- package/dist/{chunk-GRJC2F3P.js → chunk-WWPXJKN4.js} +3 -3
- package/dist/{chunk-Q2LABBI5.js → chunk-XLZ734N3.js} +3 -3
- package/dist/{chunk-IOAG43ER.js → chunk-XMD26PDY.js} +10 -12
- package/dist/chunk-XMD26PDY.js.map +1 -0
- package/dist/{chunk-ZMFD77AY.js → chunk-YL27XZ6T.js} +5 -5
- package/dist/{chunk-UZTRCADY.js → chunk-YYDGGULW.js} +3426 -2208
- package/dist/chunk-YYDGGULW.js.map +1 -0
- package/dist/{cli-circuit-breaker-D4LO2S5C.js → cli-circuit-breaker-KMEJKQHZ.js} +5 -5
- package/dist/cli.js +2987 -1098
- package/dist/cli.js.map +1 -1
- package/dist/{composite-router-JFRT5WIU.js → composite-router-RGDD4TNU.js} +4 -4
- package/dist/{consensus-vote-2WUR2MN5.js → consensus-vote-Z5PEK4MM.js} +20 -20
- package/dist/{context-retriever-5S6NTZRG.js → context-retriever-4AQ3X4BA.js} +11 -12
- package/dist/doctor-deep-6WIHSJVD.js +13 -0
- package/dist/{doctor-live-HE5WX4IJ.js → doctor-live-KBPUGB2N.js} +13 -13
- package/dist/{expert-bridge-46OBG3SJ.js → expert-bridge-FXGOGERJ.js} +6 -6
- package/dist/factory-3C6ZJRL5.js +25 -0
- package/dist/factory-QT45XC23.js +15 -0
- package/dist/{improvement-review-CWQCW4QJ.js → improvement-review-EV7EKX2P.js} +7 -7
- package/dist/index.js +47 -48
- package/dist/index.js.map +1 -1
- package/dist/{init-opencode-UNWGZXLG.js → init-opencode-6U27FCUS.js} +8 -8
- package/dist/issue-triage-JSEBZBJ2.js +17 -0
- package/dist/{learning-persistence-EGY4VKKO.js → learning-persistence-SR5F4DSY.js} +3 -3
- package/dist/{pr-reviewer-helpers-PFPZQCPY.js → pr-reviewer-helpers-ZXSBKVAA.js} +6 -6
- package/dist/{registry-command-YANXNMSO.js → registry-command-QXMKIBJK.js} +4 -4
- package/dist/{repo-security-plan-EWNWYF3Y.js → repo-security-plan-3KJC6D43.js} +5 -5
- package/dist/research-helpers-synthesize-UEHRTCC5.js +14 -0
- package/dist/{routing-memory-OZVM7DA3.js → routing-memory-BQO6PUXU.js} +4 -4
- package/dist/{session-memory-KD5Y7TVD.js → session-memory-7XFRHFGO.js} +5 -5
- package/dist/setup-config-5WO4DBWX.js +11 -0
- package/dist/{setup-custom-api-PEP4D5KN.js → setup-custom-api-OSRXX3Z7.js} +6 -6
- package/dist/setup-data-dir-K2XK7ZRA.js +28 -0
- package/dist/{tool-memory-JRZFQ3PX.js → tool-memory-YRVKVPJA.js} +8 -8
- package/dist/{tool-memory-registry-adapters-QEC3YHB2.js → tool-memory-registry-adapters-UMPIJLHS.js} +3 -3
- package/dist/unified-registry-NZUP46HN.js +26 -0
- package/dist/{weather-report-4TP5YCFG.js → weather-report-WQKQQGOM.js} +4 -4
- package/package.json +1 -1
- package/dist/chunk-DJ2NGRHS.js.map +0 -1
- package/dist/chunk-GLYII4EO.js +0 -1942
- package/dist/chunk-GLYII4EO.js.map +0 -1
- package/dist/chunk-IOAG43ER.js.map +0 -1
- package/dist/chunk-NUBSJGQZ.js +0 -14
- package/dist/chunk-NUBSJGQZ.js.map +0 -1
- package/dist/chunk-OQLFRJCW.js.map +0 -1
- package/dist/chunk-UZTRCADY.js.map +0 -1
- package/dist/chunk-WPLXWTUK.js.map +0 -1
- package/dist/chunk-Y24TNAK5.js +0 -2455
- package/dist/chunk-Y24TNAK5.js.map +0 -1
- package/dist/doctor-deep-FXQN3UQZ.js +0 -13
- package/dist/factory-S67EX46S.js +0 -15
- package/dist/factory-ZXDSU5MF.js +0 -25
- package/dist/issue-triage-FA3I6DFO.js +0 -17
- package/dist/research-helpers-synthesize-TMXQFCDY.js +0 -15
- package/dist/setup-command-FRMKDYMA.js +0 -45
- package/dist/setup-config-X2UWR7X2.js +0 -11
- package/dist/unified-registry-H44QDVXY.js +0 -26
- /package/dist/{child-mcp-config-E5YGOYIM.js.map → child-mcp-config-APH7KTWD.js.map} +0 -0
- /package/dist/{chunk-3U3AAMAU.js.map → chunk-25ZTN5RI.js.map} +0 -0
- /package/dist/{chunk-KQU3HO7T.js.map → chunk-3FRBJFOX.js.map} +0 -0
- /package/dist/{chunk-45X7AGDF.js.map → chunk-5DT2LK7C.js.map} +0 -0
- /package/dist/{chunk-RGX43IEW.js.map → chunk-5WDKJA6B.js.map} +0 -0
- /package/dist/{chunk-SMPLE7KA.js.map → chunk-6DPOX5GU.js.map} +0 -0
- /package/dist/{chunk-6IDZUUC5.js.map → chunk-75J5CYUV.js.map} +0 -0
- /package/dist/{chunk-7ERIPG4P.js.map → chunk-7K4UQJD3.js.map} +0 -0
- /package/dist/{chunk-OC5EBGLD.js.map → chunk-7PCOAMGG.js.map} +0 -0
- /package/dist/{chunk-CEHYUQTT.js.map → chunk-7RRQSUX4.js.map} +0 -0
- /package/dist/{chunk-HW3BCQKG.js.map → chunk-BI6L5HAS.js.map} +0 -0
- /package/dist/{chunk-TYNKSYWN.js.map → chunk-BRPWBUSX.js.map} +0 -0
- /package/dist/{chunk-6MSKPFFM.js.map → chunk-BV4L3SWR.js.map} +0 -0
- /package/dist/{chunk-XSOMMTPM.js.map → chunk-CBFZSAUL.js.map} +0 -0
- /package/dist/{chunk-XHDAHIAJ.js.map → chunk-CD24GOBY.js.map} +0 -0
- /package/dist/{chunk-LRUPAIVW.js.map → chunk-FEC3PFSO.js.map} +0 -0
- /package/dist/{chunk-IMI6LRZ2.js.map → chunk-FLX3LARU.js.map} +0 -0
- /package/dist/{chunk-R4TX27OZ.js.map → chunk-FZ7ACQTB.js.map} +0 -0
- /package/dist/{chunk-M5KWBRUY.js.map → chunk-HHHB3R7L.js.map} +0 -0
- /package/dist/{chunk-2HUC6NZN.js.map → chunk-HHLCAWAV.js.map} +0 -0
- /package/dist/{chunk-HGO7LVRL.js.map → chunk-JGQ3YQP5.js.map} +0 -0
- /package/dist/{chunk-SJMQFZCV.js.map → chunk-JUZRCQJI.js.map} +0 -0
- /package/dist/{chunk-XIIUIBSX.js.map → chunk-KGFFEQTN.js.map} +0 -0
- /package/dist/{chunk-ULAF5ULM.js.map → chunk-QE3FY3DG.js.map} +0 -0
- /package/dist/{chunk-SNJNRDKZ.js.map → chunk-RQV5ZUXT.js.map} +0 -0
- /package/dist/{chunk-LVA53Q4Y.js.map → chunk-TCKP3H54.js.map} +0 -0
- /package/dist/{chunk-KNDUA6HH.js.map → chunk-UCVDEZGK.js.map} +0 -0
- /package/dist/{chunk-T25FZOJ3.js.map → chunk-VP7KIRQQ.js.map} +0 -0
- /package/dist/{chunk-PWUPYWJE.js.map → chunk-WJA3TLFH.js.map} +0 -0
- /package/dist/{chunk-GRJC2F3P.js.map → chunk-WWPXJKN4.js.map} +0 -0
- /package/dist/{chunk-Q2LABBI5.js.map → chunk-XLZ734N3.js.map} +0 -0
- /package/dist/{chunk-ZMFD77AY.js.map → chunk-YL27XZ6T.js.map} +0 -0
- /package/dist/{cli-circuit-breaker-D4LO2S5C.js.map → cli-circuit-breaker-KMEJKQHZ.js.map} +0 -0
- /package/dist/{composite-router-JFRT5WIU.js.map → composite-router-RGDD4TNU.js.map} +0 -0
- /package/dist/{consensus-vote-2WUR2MN5.js.map → consensus-vote-Z5PEK4MM.js.map} +0 -0
- /package/dist/{context-retriever-5S6NTZRG.js.map → context-retriever-4AQ3X4BA.js.map} +0 -0
- /package/dist/{doctor-deep-FXQN3UQZ.js.map → doctor-deep-6WIHSJVD.js.map} +0 -0
- /package/dist/{doctor-live-HE5WX4IJ.js.map → doctor-live-KBPUGB2N.js.map} +0 -0
- /package/dist/{expert-bridge-46OBG3SJ.js.map → expert-bridge-FXGOGERJ.js.map} +0 -0
- /package/dist/{factory-S67EX46S.js.map → factory-3C6ZJRL5.js.map} +0 -0
- /package/dist/{factory-ZXDSU5MF.js.map → factory-QT45XC23.js.map} +0 -0
- /package/dist/{improvement-review-CWQCW4QJ.js.map → improvement-review-EV7EKX2P.js.map} +0 -0
- /package/dist/{init-opencode-UNWGZXLG.js.map → init-opencode-6U27FCUS.js.map} +0 -0
- /package/dist/{issue-triage-FA3I6DFO.js.map → issue-triage-JSEBZBJ2.js.map} +0 -0
- /package/dist/{learning-persistence-EGY4VKKO.js.map → learning-persistence-SR5F4DSY.js.map} +0 -0
- /package/dist/{pr-reviewer-helpers-PFPZQCPY.js.map → pr-reviewer-helpers-ZXSBKVAA.js.map} +0 -0
- /package/dist/{registry-command-YANXNMSO.js.map → registry-command-QXMKIBJK.js.map} +0 -0
- /package/dist/{repo-security-plan-EWNWYF3Y.js.map → repo-security-plan-3KJC6D43.js.map} +0 -0
- /package/dist/{research-helpers-synthesize-TMXQFCDY.js.map → research-helpers-synthesize-UEHRTCC5.js.map} +0 -0
- /package/dist/{routing-memory-OZVM7DA3.js.map → routing-memory-BQO6PUXU.js.map} +0 -0
- /package/dist/{session-memory-KD5Y7TVD.js.map → session-memory-7XFRHFGO.js.map} +0 -0
- /package/dist/{setup-command-FRMKDYMA.js.map → setup-config-5WO4DBWX.js.map} +0 -0
- /package/dist/{setup-custom-api-PEP4D5KN.js.map → setup-custom-api-OSRXX3Z7.js.map} +0 -0
- /package/dist/{setup-config-X2UWR7X2.js.map → setup-data-dir-K2XK7ZRA.js.map} +0 -0
- /package/dist/{tool-memory-JRZFQ3PX.js.map → tool-memory-YRVKVPJA.js.map} +0 -0
- /package/dist/{tool-memory-registry-adapters-QEC3YHB2.js.map → tool-memory-registry-adapters-UMPIJLHS.js.map} +0 -0
- /package/dist/{unified-registry-H44QDVXY.js.map → unified-registry-NZUP46HN.js.map} +0 -0
- /package/dist/{weather-report-4TP5YCFG.js.map → weather-report-WQKQQGOM.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/research-helpers-io.ts","../src/security/safe-path.ts","../src/cli/research-scaffold.ts"],"sourcesContent":["/**\n * Research Registry I/O Operations\n *\n * File operations for loading and saving research registry YAML files.\n * Includes path traversal protection per Issue #353.\n *\n * @see docs/research/RESEARCH_INDEX.md\n * @see Issue #237 (Epic #225)\n * @see Issue #353 (Security - Path traversal fix)\n */\n\nimport * as fs from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { resolveInsideRoot } from '../security/safe-path.js';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\nimport type { Result } from '../core/index.js';\nimport { SecurityError, getErrorMessage } from '../core/index.js';\nimport { ParseError } from '../core/types/workflow.js';\nimport type { TechniquesRegistry, PapersRegistry } from './research-types.js';\nimport { ensureRegistryFile } from './research-scaffold.js';\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\n/** Path to research registry directory relative to project root */\nexport const REGISTRY_PATH = 'docs/research/registry';\n\n/** Filename for techniques registry */\nexport const TECHNIQUES_FILE = 'techniques.yaml';\n\n/** Filename for papers registry */\nexport const PAPERS_FILE = 'papers.yaml';\n\n// =============================================================================\n// PROJECT ROOT\n// =============================================================================\n\n/**\n * Get the project root directory.\n * Note: Returns cwd since registry operations use explicit rootDir parameter\n */\nexport function getProjectRoot(): string {\n return process.cwd();\n}\n\n// =============================================================================\n// PATH VALIDATION\n// =============================================================================\n\n/**\n * Validates that a constructed path stays within the allowed root directory.\n * Prevents path traversal attacks (e.g., ../../../etc/passwd).\n *\n * @param constructedPath - The full path to validate\n * @param allowedRoot - The root directory that paths must be within\n * @returns Result with validated absolute path or SecurityError\n */\nfunction validatePath(constructedPath: string, allowedRoot: string): Result<string, SecurityError> {\n const resolved = resolveInsideRoot(constructedPath, allowedRoot);\n if (resolved === null) {\n return {\n ok: false,\n error: new SecurityError('Path traversal detected: path escapes allowed root directory', {\n context: { constructedPath, allowedRoot: resolve(allowedRoot) },\n }),\n };\n }\n return { ok: true, value: resolved };\n}\n\n// =============================================================================\n// LOAD OPERATIONS\n// =============================================================================\n\n/**\n * Load techniques registry from YAML file.\n * Validates path to prevent directory traversal attacks.\n *\n * @param rootDir - Project root directory (defaults to cwd)\n * @returns Result with TechniquesRegistry or SecurityError/ParseError\n */\nexport async function loadTechniquesRegistry(\n rootDir?: string\n): Promise<Result<TechniquesRegistry, SecurityError | ParseError>> {\n const root = rootDir ?? process.cwd();\n const filePath = join(root, REGISTRY_PATH, TECHNIQUES_FILE);\n\n const pathValidation = validatePath(filePath, root);\n if (!pathValidation.ok) {\n return pathValidation;\n }\n\n // #2470: try to scaffold an empty techniques.yaml on first run so research_*\n // workflows don't error on a fresh install. No-op when file exists.\n // When scaffold refuses (e.g. <rootDir>/docs/ doesn't exist, or\n // NEXUS_NO_SCAFFOLD=1), fall through and let readFile produce the original\n // ENOENT error — that's the existing contract.\n await ensureRegistryFile(root, TECHNIQUES_FILE);\n\n try {\n const content = await fs.readFile(pathValidation.value, 'utf-8');\n return { ok: true, value: parseYaml(content) as TechniquesRegistry };\n } catch (error) {\n const message = getErrorMessage(error);\n return { ok: false, error: new ParseError(`Failed to load techniques registry: ${message}`) };\n }\n}\n\n/**\n * Load papers registry from YAML file.\n * Validates path to prevent directory traversal attacks.\n *\n * @param rootDir - Project root directory (defaults to cwd)\n * @returns Result with PapersRegistry or SecurityError/ParseError\n */\nexport async function loadPapersRegistry(\n rootDir?: string\n): Promise<Result<PapersRegistry, SecurityError | ParseError>> {\n const root = rootDir ?? process.cwd();\n const filePath = join(root, REGISTRY_PATH, PAPERS_FILE);\n\n const pathValidation = validatePath(filePath, root);\n if (!pathValidation.ok) {\n return pathValidation;\n }\n\n // #2470: try to scaffold an empty papers.yaml on first run so research_*\n // workflows don't error on a fresh install. No-op when file exists; falls\n // through silently when scaffold refuses (no docs/ root, or NEXUS_NO_SCAFFOLD).\n await ensureRegistryFile(root, PAPERS_FILE);\n\n try {\n const content = await fs.readFile(pathValidation.value, 'utf-8');\n return { ok: true, value: parseYaml(content) as PapersRegistry };\n } catch (error) {\n const message = getErrorMessage(error);\n return { ok: false, error: new ParseError(`Failed to load papers registry: ${message}`) };\n }\n}\n\n// =============================================================================\n// SAVE OPERATIONS\n// =============================================================================\n\n/**\n * Save techniques registry to YAML file.\n * Validates path to prevent directory traversal attacks.\n *\n * @param registry - The techniques registry to save\n * @param rootDir - Project root directory (defaults to cwd)\n * @returns Result with void on success or SecurityError/ParseError on failure\n */\nexport async function saveTechniquesRegistry(\n registry: TechniquesRegistry,\n rootDir?: string\n): Promise<Result<void, SecurityError | ParseError>> {\n const root = rootDir ?? process.cwd();\n const filePath = join(root, REGISTRY_PATH, TECHNIQUES_FILE);\n\n const pathValidation = validatePath(filePath, root);\n if (!pathValidation.ok) {\n return pathValidation;\n }\n\n try {\n const content = stringifyYaml(registry, { lineWidth: 100 });\n await fs.writeFile(pathValidation.value, content, 'utf-8');\n return { ok: true, value: undefined };\n } catch (error) {\n const message = getErrorMessage(error);\n return { ok: false, error: new ParseError(`Failed to save techniques registry: ${message}`) };\n }\n}\n\n/**\n * Save papers registry to YAML file.\n * Validates path to prevent directory traversal attacks.\n *\n * @param registry - The papers registry to save\n * @param rootDir - Project root directory (defaults to cwd)\n * @returns Result with void on success or SecurityError/ParseError on failure\n */\nexport async function savePapersRegistry(\n registry: PapersRegistry,\n rootDir?: string\n): Promise<Result<void, SecurityError | ParseError>> {\n const root = rootDir ?? process.cwd();\n const filePath = join(root, REGISTRY_PATH, PAPERS_FILE);\n\n const pathValidation = validatePath(filePath, root);\n if (!pathValidation.ok) {\n return pathValidation;\n }\n\n try {\n const content = stringifyYaml(registry, { lineWidth: 100 });\n await fs.writeFile(pathValidation.value, content, 'utf-8');\n return { ok: true, value: undefined };\n } catch (error) {\n const message = getErrorMessage(error);\n return { ok: false, error: new ParseError(`Failed to save papers registry: ${message}`) };\n }\n}\n","/**\n * Safe Path — Path traversal guards for scanner-controlled inputs (#1813, #1814)\n *\n * When reading files whose path comes from untrusted input (e.g., SARIF\n * scanner output), we must verify the resolved path stays within the\n * workspace root. Without this, a malicious scanner can cause arbitrary\n * file reads whose contents are exfiltrated via downstream LLM prompts\n * (CWE-22).\n *\n * Shared helper to prevent the finding-triage/fix-generator drift that\n * required two separate fixes.\n *\n * @module security/safe-path\n */\n\nimport { resolve, sep } from 'node:path';\n\n/**\n * Resolve a scanner-supplied path against the workspace root, returning null\n * if it escapes. Null means the caller must fall back to a safe alternative\n * (e.g., scanner-provided snippet) rather than reading the file.\n *\n * @param filePath - Scanner-supplied path (may be relative or absolute)\n * @param root - Workspace root (defaults to process.cwd())\n * @returns Resolved absolute path if inside root, null otherwise\n */\nexport function resolveInsideRoot(filePath: string, root: string = process.cwd()): string | null {\n const resolvedRoot = resolve(root);\n const resolved = resolve(resolvedRoot, filePath);\n if (resolved === resolvedRoot) return resolved;\n if (resolved.startsWith(resolvedRoot + sep)) return resolved;\n return null;\n}\n","/**\n * research-scaffold — auto-create empty research registry files when missing.\n *\n * On a fresh install or in a sandboxed environment where the project doesn't\n * have `docs/research/registry/`, the research workflows previously errored\n * with `Failed to load papers registry: ENOENT`. The user has no idea what\n * to do.\n *\n * This module provides `ensureResearchRegistry()`: idempotent scaffolding\n * that creates empty YAML registries on ENOENT, announces what it did to\n * stderr (so the operator knows), and returns the path that's now safe to\n * read.\n *\n * Source: Issue #2470 (epic #2467 child).\n */\n\nimport * as fs from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { stringify as stringifyYaml } from 'yaml';\n\nimport type { Result } from '../core/index.js';\nimport { ok, err, getErrorMessage } from '../core/index.js';\nimport { ParseError } from '../core/types/workflow.js';\n\nimport { REGISTRY_PATH, PAPERS_FILE, TECHNIQUES_FILE } from './research-helpers-io.js';\nimport { parseBoolEnv } from '../config/defaults-env.js';\n\n/**\n * Names of the registry files this scaffolder knows how to create.\n * `sources.yaml` and `alignments.yaml` live alongside but are populated by\n * different code paths; this scaffolder only owns the two YAML registries\n * that block `research_query` / `research_synthesize` on a fresh install.\n */\ntype ScaffoldedFile = typeof PAPERS_FILE | typeof TECHNIQUES_FILE;\n\nconst SCHEMA_VERSION = '1.0';\n\nconst ANNOUNCED = new Set<string>();\n\nfunction announceOnce(path: string, kind: ScaffoldedFile): void {\n // De-dupe so that running multiple research commands in one session\n // produces one announcement per scaffolded file, not per call.\n if (ANNOUNCED.has(path)) return;\n ANNOUNCED.add(path);\n process.stderr.write(\n `[scaffold] Created empty ${kind} at ${path}; add entries via 'nexus-agents research add' or research_add MCP tool.\\n`\n );\n}\n\n/**\n * Operator opt-out. When set, scaffolding errors loudly with an actionable\n * message instead of silently writing files. Useful for CI and for\n * environments that want strict \"fail when state is wrong\" semantics.\n */\nfunction scaffoldDisabled(): boolean {\n return parseBoolEnv('NEXUS_NO_SCAFFOLD', false);\n}\n\nfunction emptyPapersYaml(): string {\n return stringifyYaml({ schema_version: SCHEMA_VERSION, papers: {} });\n}\n\nfunction emptyTechniquesYaml(): string {\n return stringifyYaml({ schema_version: SCHEMA_VERSION, techniques: {} });\n}\n\n/**\n * Create the registry directory + an empty YAML file if either is missing.\n * Idempotent: existing files are left untouched.\n *\n * Scaffolds only when `<rootDir>/docs/` already exists. That guard keeps\n * tests, vitest's package cwd, and random scratch directories from getting\n * a `docs/research/` subtree implicitly. Operators on a real project root\n * (which always has `docs/`, either from cloning the repo or running\n * `nexus-agents init`) still get the auto-create behavior the issue asks for.\n *\n * Returns the resolved file path on success, or a ParseError when scaffolding\n * is disabled / refused (so the caller can pass the error through unchanged\n * for backwards compat with existing call sites).\n */\nexport async function ensureRegistryFile(\n rootDir: string,\n filename: ScaffoldedFile\n): Promise<Result<string, ParseError>> {\n const filePath = resolve(rootDir, REGISTRY_PATH, filename);\n\n if (existsSync(filePath)) return ok(filePath);\n\n if (scaffoldDisabled()) {\n return err(\n new ParseError(\n `Registry file missing: ${filePath}. Scaffolding disabled (NEXUS_NO_SCAFFOLD=1). Create the file manually or unset the env var.`\n )\n );\n }\n\n // Refuse to create a docs/ subtree in directories that aren't already\n // documented project roots. The presence of `<rootDir>/docs/` is the\n // strong signal we use.\n if (!existsSync(resolve(rootDir, 'docs'))) {\n return err(\n new ParseError(\n `Registry file missing: ${filePath}. ${rootDir}/docs/ does not exist; ` +\n `refusing to create a Nexus subtree in a non-documented root. ` +\n `Run 'nexus-agents init' first, or create ${rootDir}/docs/ manually.`\n )\n );\n }\n\n try {\n await fs.mkdir(dirname(filePath), { recursive: true });\n const content = filename === PAPERS_FILE ? emptyPapersYaml() : emptyTechniquesYaml();\n await fs.writeFile(filePath, content, 'utf-8');\n announceOnce(filePath, filename);\n return ok(filePath);\n } catch (e: unknown) {\n return err(\n new ParseError(\n `Failed to scaffold ${filename} at ${filePath}: ${getErrorMessage(e)}. Set NEXUS_NO_SCAFFOLD=1 and create manually if scaffolding is unwanted.`\n )\n );\n }\n}\n\n/**\n * Convenience: scaffold both papers.yaml and techniques.yaml. Used by the\n * research workflow startup paths that need both registries available.\n */\nexport async function ensureResearchRegistry(rootDir?: string): Promise<Result<void, ParseError>> {\n const root = rootDir ?? process.cwd();\n const papers = await ensureRegistryFile(root, PAPERS_FILE);\n if (!papers.ok) return papers;\n const techniques = await ensureRegistryFile(root, TECHNIQUES_FILE);\n if (!techniques.ok) return techniques;\n return ok(undefined);\n}\n\n/**\n * Test-only reset of the announcement de-dupe set. Production code never\n * needs this; tests do because Vitest reuses process state across files.\n */\nexport function _resetAnnouncedForTests(): void {\n ANNOUNCED.clear();\n}\n"],"mappings":";;;;;;;;;;AAWA,YAAYA,SAAQ;AACpB,SAAS,MAAM,WAAAC,gBAAe;;;ACG9B,SAAS,SAAS,WAAW;AAWtB,SAAS,kBAAkB,UAAkB,OAAe,QAAQ,IAAI,GAAkB;AAC/F,QAAM,eAAe,QAAQ,IAAI;AACjC,QAAM,WAAW,QAAQ,cAAc,QAAQ;AAC/C,MAAI,aAAa,aAAc,QAAO;AACtC,MAAI,SAAS,WAAW,eAAe,GAAG,EAAG,QAAO;AACpD,SAAO;AACT;;;ADlBA,SAAS,SAAS,WAAW,aAAaC,sBAAqB;;;AEE/D,YAAY,QAAQ;AACpB,SAAS,kBAAkB;AAC3B,SAAS,SAAS,WAAAC,gBAAe;AACjC,SAAS,aAAa,qBAAqB;AAiB3C,IAAM,iBAAiB;AAEvB,IAAM,YAAY,oBAAI,IAAY;AAElC,SAAS,aAAa,MAAc,MAA4B;AAG9D,MAAI,UAAU,IAAI,IAAI,EAAG;AACzB,YAAU,IAAI,IAAI;AAClB,UAAQ,OAAO;AAAA,IACb,4BAA4B,IAAI,OAAO,IAAI;AAAA;AAAA,EAC7C;AACF;AAOA,SAAS,mBAA4B;AACnC,SAAO,aAAa,qBAAqB,KAAK;AAChD;AAEA,SAAS,kBAA0B;AACjC,SAAO,cAAc,EAAE,gBAAgB,gBAAgB,QAAQ,CAAC,EAAE,CAAC;AACrE;AAEA,SAAS,sBAA8B;AACrC,SAAO,cAAc,EAAE,gBAAgB,gBAAgB,YAAY,CAAC,EAAE,CAAC;AACzE;AAgBA,eAAsB,mBACpB,SACA,UACqC;AACrC,QAAM,WAAWC,SAAQ,SAAS,eAAe,QAAQ;AA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E,IAAI,MAAM,OAAO,OAAU;AAAA,EACtC,SAAS,OAAO;AACd,UAAM,UAAU,gBAAgB,KAAK;AACrC,WAAO,EAAE,IAAI,OAAO,OAAO,IAAI,WAAW,mCAAmC,OAAO,EAAE,EAAE;AAAA,EAC1F;AACF;","names":["fs","resolve","stringifyYaml","resolve","resolve","resolve","stringifyYaml"]}
|
|
@@ -1,5 +1,50 @@
|
|
|
1
|
+
// src/config/nexus-data-dir.ts
|
|
2
|
+
import {
|
|
3
|
+
accessSync as accessSync2,
|
|
4
|
+
constants as fsConstants,
|
|
5
|
+
copyFileSync,
|
|
6
|
+
existsSync as existsSync4,
|
|
7
|
+
mkdirSync,
|
|
8
|
+
realpathSync as realpathSync2,
|
|
9
|
+
renameSync,
|
|
10
|
+
statSync as statSync3,
|
|
11
|
+
unlinkSync
|
|
12
|
+
} from "fs";
|
|
13
|
+
import { homedir as homedir2 } from "os";
|
|
14
|
+
import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2, resolve as resolve3 } from "path";
|
|
15
|
+
|
|
16
|
+
// src/config/sandbox-detection.ts
|
|
17
|
+
import { existsSync, readFileSync } from "fs";
|
|
18
|
+
function detectSandbox() {
|
|
19
|
+
const flavorRaw = process.env["NEXUS_SANDBOX"]?.trim();
|
|
20
|
+
const flavor = flavorRaw !== void 0 && flavorRaw !== "" ? flavorRaw : void 0;
|
|
21
|
+
const active = flavor !== void 0;
|
|
22
|
+
const rootRaw = process.env["NEXUS_SANDBOX_ROOT"]?.trim();
|
|
23
|
+
const root = rootRaw !== void 0 && rootRaw !== "" ? rootRaw : void 0;
|
|
24
|
+
return {
|
|
25
|
+
active,
|
|
26
|
+
flavor,
|
|
27
|
+
root,
|
|
28
|
+
heuristicMatch: detectContainerHeuristic()
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function detectContainerHeuristic() {
|
|
32
|
+
try {
|
|
33
|
+
if (existsSync("/.dockerenv")) return "docker";
|
|
34
|
+
if (existsSync("/run/.containerenv")) return "podman";
|
|
35
|
+
if (existsSync("/proc/1/cgroup")) {
|
|
36
|
+
const cgroup = readFileSync("/proc/1/cgroup", "utf8");
|
|
37
|
+
if (/\bdocker\b/.test(cgroup)) return "docker";
|
|
38
|
+
if (/\bcontainerd\b/.test(cgroup)) return "docker";
|
|
39
|
+
}
|
|
40
|
+
return "unknown";
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
1
46
|
// src/config/repo-root-detection.ts
|
|
2
|
-
import { existsSync, readFileSync, realpathSync, statSync } from "fs";
|
|
47
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync, statSync } from "fs";
|
|
3
48
|
import { dirname, isAbsolute, resolve } from "path";
|
|
4
49
|
function findRepoRoot(start) {
|
|
5
50
|
if (!isAbsolute(start)) {
|
|
@@ -38,12 +83,12 @@ function findRepoRoot(start) {
|
|
|
38
83
|
}
|
|
39
84
|
function isRepoRoot(dir) {
|
|
40
85
|
const gitPath = `${dir}/.git`;
|
|
41
|
-
if (!
|
|
86
|
+
if (!existsSync2(gitPath)) return false;
|
|
42
87
|
try {
|
|
43
88
|
const st = statSync(gitPath);
|
|
44
89
|
if (st.isDirectory()) return true;
|
|
45
90
|
if (st.isFile()) {
|
|
46
|
-
const head =
|
|
91
|
+
const head = readFileSync2(gitPath, "utf-8").slice(0, 256);
|
|
47
92
|
return head.startsWith("gitdir:");
|
|
48
93
|
}
|
|
49
94
|
} catch {
|
|
@@ -53,7 +98,7 @@ function isRepoRoot(dir) {
|
|
|
53
98
|
}
|
|
54
99
|
|
|
55
100
|
// src/config/portable-mode.ts
|
|
56
|
-
import { accessSync, constants, existsSync as
|
|
101
|
+
import { accessSync, constants, existsSync as existsSync3, readFileSync as readFileSync3, appendFileSync, statSync as statSync2 } from "fs";
|
|
57
102
|
import { homedir } from "os";
|
|
58
103
|
import { join, resolve as resolve2 } from "path";
|
|
59
104
|
var SANDBOX_ENV_VARS = [
|
|
@@ -68,7 +113,7 @@ var DETECTED = false;
|
|
|
68
113
|
function isHomeWritable() {
|
|
69
114
|
try {
|
|
70
115
|
const home = homedir();
|
|
71
|
-
if (!
|
|
116
|
+
if (!existsSync3(home)) return false;
|
|
72
117
|
accessSync(home, constants.W_OK);
|
|
73
118
|
return true;
|
|
74
119
|
} catch {
|
|
@@ -132,7 +177,7 @@ function applyPortableMode(cwd = process.cwd()) {
|
|
|
132
177
|
function isInsideGitRepo(cwd) {
|
|
133
178
|
try {
|
|
134
179
|
const gitDir = join(cwd, ".git");
|
|
135
|
-
return
|
|
180
|
+
return existsSync3(gitDir) && statSync2(gitDir).isDirectory();
|
|
136
181
|
} catch {
|
|
137
182
|
return false;
|
|
138
183
|
}
|
|
@@ -140,7 +185,7 @@ function isInsideGitRepo(cwd) {
|
|
|
140
185
|
function ensureGitignored(cwd, entry) {
|
|
141
186
|
const path = join(cwd, ".gitignore");
|
|
142
187
|
try {
|
|
143
|
-
const existing =
|
|
188
|
+
const existing = existsSync3(path) ? readFileSync3(path, "utf-8") : "";
|
|
144
189
|
const lines = existing.split("\n").map((l) => l.trim());
|
|
145
190
|
if (lines.includes(entry) || lines.includes(entry.replace(/\/$/, ""))) return;
|
|
146
191
|
const sep = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
|
|
@@ -159,51 +204,6 @@ function ensureGitignored(cwd, entry) {
|
|
|
159
204
|
}
|
|
160
205
|
}
|
|
161
206
|
|
|
162
|
-
// src/config/nexus-data-dir.ts
|
|
163
|
-
import {
|
|
164
|
-
accessSync as accessSync2,
|
|
165
|
-
constants as fsConstants,
|
|
166
|
-
copyFileSync,
|
|
167
|
-
existsSync as existsSync4,
|
|
168
|
-
mkdirSync,
|
|
169
|
-
realpathSync as realpathSync2,
|
|
170
|
-
renameSync,
|
|
171
|
-
statSync as statSync3,
|
|
172
|
-
unlinkSync
|
|
173
|
-
} from "fs";
|
|
174
|
-
import { homedir as homedir2 } from "os";
|
|
175
|
-
import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2, resolve as resolve3 } from "path";
|
|
176
|
-
|
|
177
|
-
// src/config/sandbox-detection.ts
|
|
178
|
-
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
|
|
179
|
-
function detectSandbox() {
|
|
180
|
-
const flavorRaw = process.env["NEXUS_SANDBOX"]?.trim();
|
|
181
|
-
const flavor = flavorRaw !== void 0 && flavorRaw !== "" ? flavorRaw : void 0;
|
|
182
|
-
const active = flavor !== void 0;
|
|
183
|
-
const rootRaw = process.env["NEXUS_SANDBOX_ROOT"]?.trim();
|
|
184
|
-
const root = rootRaw !== void 0 && rootRaw !== "" ? rootRaw : void 0;
|
|
185
|
-
return {
|
|
186
|
-
active,
|
|
187
|
-
flavor,
|
|
188
|
-
root,
|
|
189
|
-
heuristicMatch: detectContainerHeuristic()
|
|
190
|
-
};
|
|
191
|
-
}
|
|
192
|
-
function detectContainerHeuristic() {
|
|
193
|
-
try {
|
|
194
|
-
if (existsSync3("/.dockerenv")) return "docker";
|
|
195
|
-
if (existsSync3("/run/.containerenv")) return "podman";
|
|
196
|
-
if (existsSync3("/proc/1/cgroup")) {
|
|
197
|
-
const cgroup = readFileSync3("/proc/1/cgroup", "utf8");
|
|
198
|
-
if (/\bdocker\b/.test(cgroup)) return "docker";
|
|
199
|
-
if (/\bcontainerd\b/.test(cgroup)) return "docker";
|
|
200
|
-
}
|
|
201
|
-
return "unknown";
|
|
202
|
-
} catch {
|
|
203
|
-
return null;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
207
|
// src/config/nexus-data-dir.ts
|
|
208
208
|
var PER_REPO_SUBDIRS = /* @__PURE__ */ new Set([
|
|
209
209
|
// Scratch space for short-lived work (worktrees, prompt files, MCP configs).
|
|
@@ -383,4 +383,4 @@ export {
|
|
|
383
383
|
getPerRepoSubdirs,
|
|
384
384
|
sessionsDbPath
|
|
385
385
|
};
|
|
386
|
-
//# sourceMappingURL=chunk-
|
|
386
|
+
//# sourceMappingURL=chunk-NBMWONHE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config/nexus-data-dir.ts","../src/config/sandbox-detection.ts","../src/config/repo-root-detection.ts","../src/config/portable-mode.ts"],"sourcesContent":["/**\n * Nexus runtime data directory resolver (#2302, child of #2301).\n *\n * Returns the absolute path under which nexus-agents stores runtime state.\n * Two categories of state exist (epic #2872, vote #2876):\n *\n * - **Per-repo** state (sessions, checkpoints, traces, runs, audit,\n * pipeline, tasks) — tied to the work happening in a specific codebase.\n * When `NEXUS_REPO_PREFERRED=1` is set and the caller is inside a git\n * repo, these resolve to `<repo-root>/.nexus-agents/<subdir>/`.\n * - **Cross-repo** state (learning, voting, memory, weather, research,\n * auth, usage, models manifest) — accumulates across the operator's\n * whole workflow. Always resolves to `~/.nexus-agents/<subdir>/` so the\n * learning/routing feedback loop from #1389 / #1407 keeps working.\n *\n * Resolution order (first match wins):\n * 1. `NEXUS_DATA_DIR` env var if set + non-empty. Wins for both categories\n * — the operator's explicit choice overrides the split.\n * 2. Sandbox-mode default (#2501): when `NEXUS_SANDBOX` is set, use\n * `${NEXUS_SANDBOX_ROOT ?? '/'}/.nexus-agents`. Sandboxed deployments\n * typically mount a multi-repo root; state goes there, shared across\n * repo subfolders rather than buried inside one.\n * 3. Per-repo subdirs (when a repo root is known AND `NEXUS_REPO_PREFERRED`\n * is not explicitly `'0'`): `<repo-root>/.nexus-agents/<subdir>/`. The\n * repo root is the active workspace root when one has been set via\n * `setActiveWorkspaceRoot()` (the MCP server derives it from the client's\n * declared `roots`, MCP spec — see #3991), otherwise `findRepoRoot(cwd)`.\n * The active-root path exists because a globally-installed MCP server runs\n * with `process.cwd()` outside the repo, so cwd-based detection would\n * wrongly route per-repo state to homedir. Auto-adds `.nexus-agents/` to\n * the repo's `.gitignore` on first resolution (fail-closed).\n * 4. Cross-repo subdirs when `~/.nexus-agents/` is unwritable AND we're\n * in a repo: per-repo fallback at `<repo-root>/.nexus-agents/<subdir>/`\n * with one-time stderr announce. Issue #2888 — gives sandbox users\n * a working `research/`, `memory/`, etc. without env-var wrangling\n * while preserving the vote #2876 default for normal-machine users.\n * 5. `<homedir>/.nexus-agents` (cross-repo state on normal machines,\n * plus everything when not in a git repo or when\n * `NEXUS_REPO_PREFERRED=0`).\n *\n * `NEXUS_REPO_PREFERRED` defaults **ON** as of this release per vote\n * #2876. Escape hatches preserved:\n * - `NEXUS_REPO_PREFERRED=0` — fully opt out (homedir for everything).\n * - `NEXUS_DATA_DIR=~/.nexus-agents` — explicit override wins over\n * the tier and the categorization both.\n * - `nexus-agents migrate` (#2879) — relocate existing homedir state\n * into `<repo>/.nexus-agents/` before flipping in production.\n *\n * @module config/nexus-data-dir\n */\n\nimport {\n accessSync,\n constants as fsConstants,\n copyFileSync,\n existsSync,\n mkdirSync,\n realpathSync,\n renameSync,\n statSync,\n unlinkSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\n\nimport { detectSandbox } from './sandbox-detection.js';\nimport { findRepoRoot } from './repo-root-detection.js';\nimport { ensureGitignored } from './portable-mode.js';\n\n/**\n * Subdirs scoped to a single repo's work (per the epic #2872 vote).\n * When `NEXUS_REPO_PREFERRED=1` and the caller is inside a git repo, these\n * route to `<repo-root>/.nexus-agents/`; otherwise homedir. The complement\n * (everything not in this set) always goes to homedir so cross-project\n * learning state stays intact.\n *\n * Source-of-truth for the categorization: vote #2876 conditions + audit\n * thread on epic #2872. Adding a new entry here is the appropriate way to\n * mark new state as per-repo — do that as a deliberate decision, not by\n * default.\n */\nconst PER_REPO_SUBDIRS: ReadonlySet<string> = new Set([\n // Scratch space for short-lived work (worktrees, prompt files, MCP configs).\n // Per-repo because a throwaway worktree of repo A is meaningless to repo B,\n // and because containing it here keeps it inside the already-gitignored\n // `.nexus-agents/` tree instead of accumulating in a shared `/tmp` nobody\n // reaps. A full `/tmp` is not a theoretical problem: it silently broke this\n // repo's own test suite, with ~1,100 files failing to COLLECT and zero\n // assertion failures, which reads like a code fault and is not one.\n 'tmp',\n 'sessions',\n 'checkpoints',\n 'traces',\n 'runs',\n 'audit',\n 'pipeline',\n 'tasks',\n // Async-mode job results (#3042 / epic #2631). Tied to work happening\n // in a specific codebase — a job dispatched on repo A shouldn't be\n // polled-against on repo B, which would happen if jobs/ were homedir-scoped.\n 'jobs',\n // CI health-check events (#3076 / #3084). Per-repo because outages\n // reported via `ci_health_check({ repo })` are repo-correlated; a wedge\n // on repo A's queue does not predict repo B's health.\n 'ci-health',\n // Governance artifacts — the runtime authentic-vote-record ledger\n // (`governance/vote-records.jsonl`, #3897/#3927/#3991). Per-repo because a\n // promotion proposal is scoped to the codebase being changed; with\n // `NEXUS_REPO_PREFERRED=1` (default) these route to\n // `<repo>/.nexus-agents/governance/` (gitignored), and to\n // `~/.nexus-agents/governance/` otherwise (global / non-repo install). This\n // is DISTINCT from the committed `<repo>/governance/vote-records.jsonl`\n // ledger the promotion gate reads — that artifact is reached only via the\n // explicit `NEXUS_VOTE_RECORDS_PATH` override (#3991).\n 'governance',\n]);\n\n/** Returns the absolute path to the nexus-agents data directory. */\nexport function getNexusDataDir(): string {\n const fromEnv = process.env['NEXUS_DATA_DIR']?.trim();\n if (fromEnv !== undefined && fromEnv !== '') {\n return resolve(fromEnv);\n }\n const sandbox = detectSandbox();\n if (sandbox.active) {\n return resolve(sandbox.root ?? '/', '.nexus-agents');\n }\n return join(homedir(), '.nexus-agents');\n}\n\n/**\n * No-op kept for source-compatibility with consumers that called this\n * earlier in development. The resolver is no longer cached, so resetting\n * is unnecessary. Kept exported (rather than removed) to avoid breaking\n * imports in tests that may have already adopted it.\n */\nexport function resetNexusDataDirCache(): void {\n // intentionally empty — see module docstring\n}\n\n/**\n * Tracks per-process state for the auto-gitignore wiring: we only need\n * to (a) probe + append to `.gitignore` once per repo, and (b) bail\n * cleanly if the operator has explicitly silenced the auto-add via\n * `NEXUS_GITIGNORE_AUTO=0`. Reset in tests via the helper below.\n */\nconst gitignoredRoots = new Set<string>();\n\n/** Test helper — clears the auto-gitignore \"already did this\" memo. */\nexport function _resetGitignoreMemoForTests(): void {\n gitignoredRoots.clear();\n}\n\n/**\n * Active workspace root, when known from a source more authoritative than\n * `process.cwd()`. Set by the MCP server (#3991) from the client's declared\n * `roots` (MCP spec) once the initialize handshake completes, because a\n * globally-installed server runs with cwd OUTSIDE the repo being worked on —\n * so cwd-based repo detection would route per-repo `.nexus-agents` state to\n * homedir instead of `<repo>/.nexus-agents/`. CLI / in-repo callers never set\n * this, so they keep resolving via `findRepoRoot(cwd)` exactly as before.\n */\nlet activeWorkspaceRoot: string | undefined;\n\n/**\n * Records the active workspace root for repo-scoped data resolution. The\n * value is cross-trust-boundary input (it arrives over the MCP transport from\n * the client), so it is validated before use: resolved to an absolute path,\n * canonicalized via `realpathSync` (defeats symlink games), and required to\n * be an existing directory. Returns `true` when accepted, `false` when the\n * value is empty/invalid (in which case the previous root is left untouched).\n * Passing `null`/empty explicitly clears any previously-set root.\n */\nexport function setActiveWorkspaceRoot(root: string | null | undefined): boolean {\n const trimmed = root?.trim();\n if (trimmed === undefined || trimmed === '') {\n activeWorkspaceRoot = undefined;\n return false;\n }\n try {\n const canonical = realpathSync(resolve(trimmed));\n if (!isAbsolute(canonical) || !statSync(canonical).isDirectory()) return false;\n activeWorkspaceRoot = canonical;\n return true;\n } catch {\n // Nonexistent path, permission error, or broken symlink — reject and keep\n // whatever was set before so a bad late signal can't corrupt resolution.\n return false;\n }\n}\n\n/** Returns the active workspace root if one has been set, else `undefined`. */\nexport function getActiveWorkspaceRoot(): string | undefined {\n return activeWorkspaceRoot;\n}\n\n/** Test helper — clears the active workspace root memo. */\nexport function _resetActiveWorkspaceRootForTests(): void {\n activeWorkspaceRoot = undefined;\n}\n\n/**\n * Returns the repo-scoped `.nexus-agents/` directory if all of the\n * following hold: `NEXUS_REPO_PREFERRED` is NOT explicitly `'0'` (it\n * defaults ON as of vote #2876), `NEXUS_DATA_DIR` is not explicitly set\n * (explicit override always wins), no sandbox is active, and a repo root is\n * known — either the active workspace root (set via\n * `setActiveWorkspaceRoot()`) or an ancestor `.git` found by\n * `findRepoRoot(cwd)`.\n *\n * Side effect: on the first successful resolution per process per repo,\n * appends `.nexus-agents/` to the repo's `.gitignore` if not already\n * present. The operator can silence this with `NEXUS_GITIGNORE_AUTO=0`\n * (e.g. on CI runners with a frozen working tree).\n *\n * Returns `null` when any precondition fails; callers fall back to\n * `getNexusDataDir()` (homedir).\n */\nexport function getNexusRepoDir(): string | null {\n if (process.env['NEXUS_REPO_PREFERRED'] === '0') return null;\n const fromEnv = process.env['NEXUS_DATA_DIR']?.trim();\n if (fromEnv !== undefined && fromEnv !== '') return null;\n if (detectSandbox().active) return null;\n // Prefer the MCP-client-declared workspace root (#3991) when the server has\n // set it; fall back to walking up from cwd for CLI / in-repo callers.\n const root = activeWorkspaceRoot ?? findRepoRoot(process.cwd());\n if (root === null) return null;\n maybeAutoGitignore(root);\n return join(root, '.nexus-agents');\n}\n\n/**\n * Best-effort fail-closed wiring: once per process per repo, ensure\n * `.nexus-agents/` is in `<repo>/.gitignore`. Silenced via\n * `NEXUS_GITIGNORE_AUTO=0`. Failures are non-fatal — the helper logs\n * to stderr and continues.\n */\nfunction maybeAutoGitignore(repoRoot: string): void {\n if (process.env['NEXUS_GITIGNORE_AUTO'] === '0') return;\n if (gitignoredRoots.has(repoRoot)) return;\n gitignoredRoots.add(repoRoot);\n // Only attempt when the repo root looks real — avoid spamming stderr\n // from temp-dir test fixtures that race the lifecycle.\n if (!existsSync(repoRoot)) return;\n ensureGitignored(repoRoot, '.nexus-agents/');\n}\n\n/**\n * Per-process memo: was the homedir base directory found writable on first\n * probe? Used to short-circuit the sandbox-fallback decision in\n * `nexusDataPath()` without spending a syscall on every call.\n */\nlet homedirWritable: boolean | undefined;\n\n/** Per-process memo: have we already announced a fallback for this subdir? */\nconst announcedFallbacks = new Set<string>();\n\n/** Test helper — clears the homedir-writability + announcement memos. */\nexport function _resetWritabilityMemoForTests(): void {\n homedirWritable = undefined;\n announcedFallbacks.clear();\n}\n\n/**\n * Returns true if `getNexusDataDir()` resolves to a writable location. Probed\n * once per process and memo'd — flips the sandbox-fallback on/off for\n * cross-repo subdirs. `mkdirSync(recursive: true)` is the safest probe\n * because it both creates the dir if missing and surfaces ENOENT/EACCES\n * issues at the same point. Failures here are non-fatal — they just route\n * cross-repo state to the per-repo fallback (issue #2888).\n */\nfunction isHomedirBaseWritable(): boolean {\n if (homedirWritable !== undefined) return homedirWritable;\n const base = getNexusDataDir();\n try {\n mkdirSync(base, { recursive: true });\n accessSync(base, fsConstants.W_OK);\n homedirWritable = true;\n } catch {\n homedirWritable = false;\n }\n return homedirWritable;\n}\n\n/**\n * Emit a one-time stderr warning when a cross-repo subdir falls back to\n * the per-repo location. Operators in sandboxes get a clear signal about\n * what happened without per-call noise.\n */\nfunction announceCrossRepoFallback(subdir: string, repoPath: string): void {\n if (announcedFallbacks.has(subdir)) return;\n announcedFallbacks.add(subdir);\n process.stderr.write(\n `[nexus] ${subdir}: homedir ~/.nexus-agents is not writable; ` +\n `using per-repo fallback at ${repoPath}. See docs/guides/SANDBOXED-USAGE.md.\\n`\n );\n}\n\n/**\n * Returns a path joined under the appropriate data directory for the\n * given subdir.\n *\n * Routing decision (first match wins):\n * 1. **Per-repo subdir + in a repo + `NEXUS_REPO_PREFERRED` not '0'** →\n * `<repo>/.nexus-agents/<subdir>/...`. Standard behavior since #2884.\n * 2. **Cross-repo subdir + homedir unwritable + in a repo** →\n * `<repo>/.nexus-agents/<subdir>/...` as a sandbox-friendly fallback\n * (issue #2888). Emits a one-time stderr warning per subdir.\n * 3. **Otherwise** → `<homedir>/.nexus-agents/<subdir>/...`. If homedir\n * is also unwritable, the actual write will surface the error.\n *\n * Existing callers don't need to change — the routing decision is driven\n * by the first segment, not by caller-declared intent.\n */\nexport function nexusDataPath(...segments: string[]): string {\n const first = segments[0];\n\n // Tier 1: per-repo subdir + repo-preferred default.\n if (first !== undefined && PER_REPO_SUBDIRS.has(first)) {\n const repoDir = getNexusRepoDir();\n if (repoDir !== null) {\n return join(repoDir, ...segments);\n }\n }\n\n // Tier 2: cross-repo subdir but homedir isn't reachable. Fall back to\n // the per-repo location if we're in a repo, so sandbox users get a\n // working `research/`, `memory/`, etc. without manual env-var setup.\n // Vote #2876 preserved: this only fires when homedir is physically\n // unreachable; normal-machine users see no change.\n if (first !== undefined && !isHomedirBaseWritable()) {\n const repoDir = getNexusRepoDir();\n if (repoDir !== null) {\n const fallbackPath = join(repoDir, ...segments);\n announceCrossRepoFallback(first, fallbackPath);\n return fallbackPath;\n }\n // No repo to fall back to AND homedir unreachable — return the\n // homedir path anyway. The caller's eventual write will surface\n // the underlying EACCES/ENOENT, which is the right error to show\n // because the environment is genuinely broken at that point.\n }\n\n return join(getNexusDataDir(), ...segments);\n}\n\n/**\n * Like `nexusDataPath()` but eagerly creates the parent directory so\n * callers don't have to remember `mkdirSync(dirname(p), { recursive: true })`\n * before every write. Issue #2890. Use when the returned path will be\n * written to immediately; for read-only resolution prefer `nexusDataPath()`.\n *\n * If the call resolves to a directory (single segment or no segments),\n * the target IS the resolved path. If it resolves to a file (multiple\n * segments), the target is its parent.\n */\nexport function nexusDataPathEnsure(...segments: string[]): string {\n const resolved = nexusDataPath(...segments);\n const target = segments.length > 1 ? dirname(resolved) : resolved;\n mkdirSync(target, { recursive: true });\n return resolved;\n}\n\n/**\n * Explicitly homedir-scoped path. Use this in code that handles\n * cross-project state (routing memory, model registry cache, auth,\n * research catalog) where you want a hard guarantee that the resolver\n * never routes per-repo, even if a new subdir gets accidentally added\n * to the `PER_REPO_SUBDIRS` allowlist later.\n */\nexport function nexusSharedPath(...segments: string[]): string {\n return join(getNexusDataDir(), ...segments);\n}\n\n/**\n * Returns the read-only categorization used by `nexusDataPath()`.\n * Exposed for tests and for tooling that wants to introspect which\n * subdirs are per-repo (e.g. the `nexus-agents migrate` command).\n */\nexport function getPerRepoSubdirs(): ReadonlySet<string> {\n return PER_REPO_SUBDIRS;\n}\n\n/** Per-process memo — the legacy session-DB relocation runs at most once. */\nlet legacySessionsDbMigrated = false;\n\n/** Test helper — clears the session-DB migration \"already did this\" memo. */\nexport function _resetSessionsDbMigrationMemoForTests(): void {\n legacySessionsDbMigrated = false;\n}\n\n/** SQLite sidecar suffixes that must travel with the main DB file. */\nconst SQLITE_SIDECAR_SUFFIXES = ['', '-wal', '-shm', '-journal'] as const;\n\n/**\n * Resolves the session-database path, performing a one-time relocation\n * of any pre-#2902 database on the first call per process.\n *\n * The session DB is per-repo episodic state and belongs in the\n * `sessions/` bucket alongside the session journals — vote #2876\n * categorized `sessions/` as per-repo, and issue #2902 (consensus\n * 3/3) extended that to the DB. Before #2902 the DB resolved via\n * `nexusDataPath('sessions.db')`; because `sessions.db` is not a\n * per-repo first segment, that landed cross-repo at\n * `~/.nexus-agents/sessions.db`, so a DB started in one repo leaked\n * into every other repo.\n *\n * If a legacy DB exists at the old location and none exists at the\n * new one, the legacy file (and any SQLite sidecars) is moved so\n * existing session history is preserved rather than silently\n * orphaned. The move is best-effort: a failure leaves the legacy DB\n * untouched for manual recovery and the caller gets a fresh DB at the\n * new path. `NEXUS_DATA_DIR` / `NEXUS_REPO_PREFERRED` / the\n * `NEXUS_SESSIONS_DB` override all sit upstream of this resolver.\n */\nexport function sessionsDbPath(): string {\n const target = nexusDataPath('sessions', 'sessions.db');\n if (!legacySessionsDbMigrated) {\n legacySessionsDbMigrated = true;\n migrateLegacySessionsDb(target);\n }\n return target;\n}\n\n/** One-time relocation of a pre-#2902 session DB. Best-effort — see `sessionsDbPath`. */\nfunction migrateLegacySessionsDb(target: string): void {\n const legacy = nexusDataPath('sessions.db'); // pre-#2902 resolution\n if (legacy === target || !existsSync(legacy) || existsSync(target)) return;\n try {\n mkdirSync(dirname(target), { recursive: true });\n for (const suffix of SQLITE_SIDECAR_SUFFIXES) {\n const from = `${legacy}${suffix}`;\n if (existsSync(from)) moveFile(from, `${target}${suffix}`);\n }\n } catch {\n // Best-effort — a migration failure must never break session storage.\n }\n}\n\n/** Moves a file, falling back to copy+unlink across a filesystem boundary. */\nfunction moveFile(from: string, to: string): void {\n try {\n renameSync(from, to);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EXDEV') throw err;\n copyFileSync(from, to);\n unlinkSync(from);\n }\n}\n","/**\n * Sandbox detection (#2501, child 1 of epic #2500).\n *\n * nexus-agents needs to know whether it's running inside a host-provided\n * sandbox (Docker Desktop Sandbox + OpenCode, Codex sandbox, locked-down\n * CI runner) so it can adjust behaviour:\n *\n * - default `NEXUS_DATA_DIR` to the multi-repo root rather than `~/...`\n * - skip CLI subprocess detection (binaries aren't there)\n * - fail-fast when the gateway is unreachable instead of degrading\n * - suppress diagnostics that don't apply\n *\n * The signal is **explicit**: the image author (Dockerfile, devcontainer,\n * harness wrapper) sets `NEXUS_SANDBOX=<flavor>`. The flavor string is\n * for diagnostics + per-flavor branching (`docker-opencode`, `codex`,\n * `claude-code`, `ci-restricted`, …); presence is the on/off signal.\n *\n * A heuristic check runs alongside for verification — if `NEXUS_SANDBOX`\n * claims `docker-opencode` but `/.dockerenv` is missing, that's a\n * misconfiguration worth surfacing to the operator.\n *\n * @module config/sandbox-detection\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\n\n/**\n * Heuristic detection result. Independent from the explicit\n * `NEXUS_SANDBOX` env var; produced by inspecting filesystem markers.\n */\nexport type SandboxHeuristic = 'docker' | 'podman' | 'unknown' | null;\n\nexport interface SandboxInfo {\n /**\n * True iff `NEXUS_SANDBOX` is set + non-empty. The explicit signal\n * the rest of the codebase keys off — never `true` by heuristic alone.\n */\n readonly active: boolean;\n /**\n * Operator-supplied flavor string, e.g. `docker-opencode`. Undefined\n * when `active === false` or the env var is empty.\n */\n readonly flavor: string | undefined;\n /**\n * Multi-repo root the user mounted. From `NEXUS_SANDBOX_ROOT`. Undefined\n * when unset; consumers that need a default substitute `/`.\n */\n readonly root: string | undefined;\n /**\n * Independent heuristic match — `null` when we couldn't run the check,\n * `'unknown'` when ran but no marker matched. Used by `doctor` to flag\n * mismatches between the explicit signal and the runtime environment.\n */\n readonly heuristicMatch: SandboxHeuristic;\n}\n\n/**\n * Detect whether nexus-agents is running inside a host-provided sandbox.\n * Pure read of env + filesystem; no caching (cheap enough to recompute,\n * and tests routinely mutate process.env).\n */\nexport function detectSandbox(): SandboxInfo {\n const flavorRaw = process.env['NEXUS_SANDBOX']?.trim();\n const flavor = flavorRaw !== undefined && flavorRaw !== '' ? flavorRaw : undefined;\n const active = flavor !== undefined;\n\n const rootRaw = process.env['NEXUS_SANDBOX_ROOT']?.trim();\n const root = rootRaw !== undefined && rootRaw !== '' ? rootRaw : undefined;\n\n return {\n active,\n flavor,\n root,\n heuristicMatch: detectContainerHeuristic(),\n };\n}\n\n/**\n * Look for filesystem markers indicating a container runtime. Used as a\n * cross-check against the explicit `NEXUS_SANDBOX` signal.\n *\n * Order of checks:\n * 1. `/.dockerenv` (Docker)\n * 2. `/run/.containerenv` (Podman)\n * 3. `/proc/1/cgroup` containing `docker` or `containerd` strings\n *\n * Returns `null` when none of the checks could run (non-Linux host with\n * no `/proc`, sandbox blocks `existsSync`, etc.) — distinct from\n * `'unknown'` (checks ran, no marker matched) so the doctor message can\n * differentiate \"we couldn't tell\" from \"we checked, no container\".\n */\nfunction detectContainerHeuristic(): SandboxHeuristic {\n try {\n if (existsSync('/.dockerenv')) return 'docker';\n if (existsSync('/run/.containerenv')) return 'podman';\n if (existsSync('/proc/1/cgroup')) {\n const cgroup = readFileSync('/proc/1/cgroup', 'utf8');\n if (/\\bdocker\\b/.test(cgroup)) return 'docker';\n if (/\\bcontainerd\\b/.test(cgroup)) return 'docker';\n }\n return 'unknown';\n } catch {\n return null;\n }\n}\n","/**\n * Repo-root detection — walks upward from a starting directory looking for\n * `.git` so callers can scope state to the current git repo. Built for\n * epic #2872 (issue #2882) to support the per-repo `.nexus-agents/` data\n * directory ratified by vote #2876.\n *\n * Defenses adopted:\n * - Walks upward but stops at filesystem root (no infinite loop on\n * symlinks-to-self).\n * - Stops at filesystem boundary (different `stat.dev`) — refuses to\n * escape across mount points. Prevents a sandboxed workdir from\n * resolving a `.git` on the host filesystem.\n * - Detects git worktrees: `.git` may be a *file* containing\n * `gitdir: <path>` rather than a directory.\n * - Realpath's the final root and rejects results that escape the\n * starting cwd by symlink.\n *\n * Deferred (tracked separately; not blocking #2882):\n * - CVE-2022-24765-style ownership check (refuse `.git` owned by a\n * different uid than the running process). The git CLI added\n * `safe.directory` for this; we don't have a comparable allowlist\n * surface yet. In CI the heuristic is too noisy to be useful\n * (runners often clone as a different uid than the workload).\n * File-system isolation (the `stat.dev` check above) covers the\n * bulk of the attack class.\n *\n * @module config/repo-root-detection\n */\n\nimport { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';\nimport { dirname, isAbsolute, resolve } from 'node:path';\n\n/**\n * Walks upward from `start` looking for `.git` (file or directory).\n * Returns the absolute path to the directory containing it, or `null`.\n *\n * Worktrees: a `.git` file (not dir) with contents `gitdir: <path>` is\n * still recognised as marking the repo root. The pointed-to gitdir is\n * NOT followed — we just need the worktree's own root.\n *\n * Filesystem boundary: stops walking if the next ancestor lives on a\n * different filesystem (different `stat.dev`). This prevents a workdir\n * mounted inside a sandbox from finding a host-side `.git`.\n */\nexport function findRepoRoot(start: string): string | null {\n if (!isAbsolute(start)) {\n start = resolve(start);\n }\n\n let current: string;\n try {\n current = realpathSync(start);\n } catch {\n return null;\n }\n\n let startDev: number | undefined;\n try {\n startDev = statSync(current).dev;\n } catch {\n return null;\n }\n\n // Walk up. Depth cap is paranoid but bounds the loop on pathological\n // symlinks even though realpathSync above should already prevent cycles.\n for (let i = 0; i < 64; i++) {\n if (isRepoRoot(current)) {\n return current;\n }\n const parent = dirname(current);\n if (parent === current) {\n // Hit filesystem root.\n return null;\n }\n try {\n if (statSync(parent).dev !== startDev) {\n // Crossed a mount point; refuse to escape.\n return null;\n }\n } catch {\n return null;\n }\n current = parent;\n }\n return null;\n}\n\n/** True iff `dir/.git` exists as a directory or a git-worktree marker file. */\nexport function isRepoRoot(dir: string): boolean {\n const gitPath = `${dir}/.git`;\n if (!existsSync(gitPath)) return false;\n try {\n const st = statSync(gitPath);\n if (st.isDirectory()) return true;\n if (st.isFile()) {\n // Worktree: first line should be `gitdir: <path>`.\n const head = readFileSync(gitPath, 'utf-8').slice(0, 256);\n return head.startsWith('gitdir:');\n }\n } catch {\n return false;\n }\n return false;\n}\n","/**\n * portable-mode — auto-detect sandboxed execution environments and\n * redirect nexus-agents data to a workspace-local directory.\n *\n * The existing `getNexusDataDir()` already respects `NEXUS_DATA_DIR` and\n * `NEXUS_PORTABLE_MODE`. This module wires up the *auto-detection* path\n * so operators running inside a Docker / restricted-FS / sandboxed\n * environment don't have to set the env vars manually — nexus-agents\n * notices and announces the flip.\n *\n * Source: Issue #2471 (epic #2467 child).\n *\n * Detection rules (first match wins):\n * 1. `NEXUS_DATA_DIR` already set → respect, no auto-detect\n * 2. `NEXUS_PORTABLE_MODE=0` → operator opted out, no auto-detect\n * 3. `NEXUS_PORTABLE_MODE=1` → portable mode, no detection needed\n * 4. Heuristic: home directory not writable\n * 5. Heuristic: container env vars set (KUBERNETES_SERVICE_HOST,\n * DOCKER_CONTAINER, ECS_CONTAINER_METADATA_URI, SANDBOX, etc.)\n *\n * When portable mode fires:\n * - Sets `process.env.NEXUS_DATA_DIR` to `<cwd>/.nexus-agents`\n * - Announces once on stderr (subsequent calls are silent)\n * - If cwd is a git repo, appends `.nexus-agents/` to .gitignore\n *\n * To force off: `NEXUS_PORTABLE_MODE=0`. To force on without heuristics:\n * `NEXUS_PORTABLE_MODE=1`. To override target dir: `NEXUS_DATA_DIR=...`.\n */\n\nimport { accessSync, constants, existsSync, readFileSync, appendFileSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\n/** Container / sandbox environment variables that strongly imply portable mode. */\nconst SANDBOX_ENV_VARS: readonly string[] = [\n 'KUBERNETES_SERVICE_HOST',\n 'DOCKER_CONTAINER',\n 'ECS_CONTAINER_METADATA_URI',\n 'ECS_CONTAINER_METADATA_URI_V4',\n 'SANDBOX',\n 'NEXUS_SANDBOX',\n];\n\nlet DETECTED = false;\n\ninterface DetectionResult {\n readonly portable: boolean;\n readonly dataDir: string;\n readonly reason:\n | 'env-data-dir'\n | 'env-opt-out'\n | 'env-opt-in'\n | 'home-unwritable'\n | 'container-env'\n | 'default';\n}\n\nfunction isHomeWritable(): boolean {\n try {\n const home = homedir();\n if (!existsSync(home)) return false;\n accessSync(home, constants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction inSandboxEnv(): boolean {\n for (const v of SANDBOX_ENV_VARS) {\n const val = process.env[v];\n if (val !== undefined && val !== '') return true;\n }\n return false;\n}\n\nfunction checkExplicitEnv(cwd: string): DetectionResult | null {\n const fromEnv = process.env['NEXUS_DATA_DIR']?.trim();\n if (fromEnv !== undefined && fromEnv !== '') {\n return { portable: false, dataDir: resolve(fromEnv), reason: 'env-data-dir' };\n }\n const portableEnv = process.env['NEXUS_PORTABLE_MODE'];\n if (portableEnv === '0' || portableEnv === 'false') {\n return { portable: false, dataDir: join(homedir(), '.nexus-agents'), reason: 'env-opt-out' };\n }\n if (portableEnv === '1' || portableEnv === 'true') {\n return { portable: true, dataDir: join(cwd, '.nexus-agents'), reason: 'env-opt-in' };\n }\n return null;\n}\n\nfunction checkHeuristics(cwd: string): DetectionResult | null {\n if (!isHomeWritable()) {\n return { portable: true, dataDir: join(cwd, '.nexus-agents'), reason: 'home-unwritable' };\n }\n if (inSandboxEnv()) {\n return { portable: true, dataDir: join(cwd, '.nexus-agents'), reason: 'container-env' };\n }\n return null;\n}\n\n/**\n * Decide whether to flip nexus-agents to portable mode and what data dir\n * to use. Pure function; no side effects beyond reading env + filesystem.\n */\nexport function detectPortableMode(cwd: string = process.cwd()): DetectionResult {\n return (\n checkExplicitEnv(cwd) ??\n checkHeuristics(cwd) ?? {\n portable: false,\n dataDir: join(homedir(), '.nexus-agents'),\n reason: 'default',\n }\n );\n}\n\n/**\n * Apply detected portable mode at process startup. Idempotent (subsequent\n * calls are no-ops). Announces on stderr once when the auto-detection\n * heuristic triggers — env-opt-in/out doesn't announce because the\n * operator already knows.\n */\nexport function applyPortableMode(cwd: string = process.cwd()): void {\n if (DETECTED) return;\n DETECTED = true;\n\n const result = detectPortableMode(cwd);\n\n // No env, no heuristic match — nothing to do.\n if (!result.portable) return;\n\n // The heuristic-driven cases announce; explicit opt-in is silent.\n if (result.reason === 'home-unwritable' || result.reason === 'container-env') {\n process.stderr.write(\n `[portable-mode] Sandbox detected (${result.reason}). Using ${result.dataDir} for all nexus-agents data.\\n` +\n ` Set NEXUS_PORTABLE_MODE=0 to override; see docs/guides/SANDBOXED-USAGE.md\\n`\n );\n }\n\n process.env['NEXUS_DATA_DIR'] = result.dataDir;\n\n if (isInsideGitRepo(cwd)) {\n ensureGitignored(cwd, '.nexus-agents/');\n }\n}\n\nfunction isInsideGitRepo(cwd: string): boolean {\n try {\n const gitDir = join(cwd, '.git');\n return existsSync(gitDir) && statSync(gitDir).isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Append `entry` to `<cwd>/.gitignore` if not already present. Stderr\n * announce on the first append. Exported because the repo-preferred\n * resolver in `nexus-data-dir.ts` reuses the same auto-gitignore behavior\n * when `<repo>/.nexus-agents/` becomes the active data dir (epic #2872).\n */\nexport function ensureGitignored(cwd: string, entry: string): void {\n const path = join(cwd, '.gitignore');\n try {\n const existing = existsSync(path) ? readFileSync(path, 'utf-8') : '';\n const lines = existing.split('\\n').map((l) => l.trim());\n if (lines.includes(entry) || lines.includes(entry.replace(/\\/$/, ''))) return;\n const sep = existing.length > 0 && !existing.endsWith('\\n') ? '\\n' : '';\n appendFileSync(path, `${sep}${entry}\\n`, 'utf-8');\n process.stderr.write(\n `[portable-mode] Added '${entry}' to ${path} so nexus-agents data is gitignored.\\n`\n );\n } catch (e: unknown) {\n // Non-fatal — operator can add the line themselves.\n const msg = e instanceof Error ? e.message : String(e);\n process.stderr.write(\n `[portable-mode] Could not auto-update ${path} (${msg}). Add '${entry}' manually if you don't want nexus-agents data tracked by git.\\n`\n );\n }\n}\n\n/** Test-only reset of the once-only state. */\nexport function _resetDetectedForTests(): void {\n DETECTED = false;\n}\n"],"mappings":";AAmDA;AAAA,EACE,cAAAA;AAAA,EACA,aAAa;AAAA,EACb;AAAA,EACA,cAAAC;AAAA,EACA;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA,YAAAC;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAAC,gBAAe;AACxB,SAAS,WAAAC,UAAS,cAAAC,aAAY,QAAAC,OAAM,WAAAC,gBAAe;;;ACvCnD,SAAS,YAAY,oBAAoB;AAqClC,SAAS,gBAA6B;AAC3C,QAAM,YAAY,QAAQ,IAAI,eAAe,GAAG,KAAK;AACrD,QAAM,SAAS,cAAc,UAAa,cAAc,KAAK,YAAY;AACzE,QAAM,SAAS,WAAW;AAE1B,QAAM,UAAU,QAAQ,IAAI,oBAAoB,GAAG,KAAK;AACxD,QAAM,OAAO,YAAY,UAAa,YAAY,KAAK,UAAU;AAEjE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB,yBAAyB;AAAA,EAC3C;AACF;AAgBA,SAAS,2BAA6C;AACpD,MAAI;AACF,QAAI,WAAW,aAAa,EAAG,QAAO;AACtC,QAAI,WAAW,oBAAoB,EAAG,QAAO;AAC7C,QAAI,WAAW,gBAAgB,GAAG;AAChC,YAAM,SAAS,aAAa,kBAAkB,MAAM;AACpD,UAAI,aAAa,KAAK,MAAM,EAAG,QAAO;AACtC,UAAI,iBAAiB,KAAK,MAAM,EAAG,QAAO;AAAA,IAC5C;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;AC3EA,SAAS,cAAAC,aAAY,gBAAAC,eAAc,cAAc,gBAAgB;AACjE,SAAS,SAAS,YAAY,eAAe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,IAA8B,SAAS,QAAS,OAAM;AAC3D,iBAAa,MAAM,EAAE;AACrB,eAAW,IAAI;AAAA,EACjB;AACF;","names":["accessSync","existsSync","realpathSync","statSync","homedir","dirname","isAbsolute","join","resolve","existsSync","readFileSync","existsSync","readFileSync","statSync","resolve","resolve","join","homedir","realpathSync","resolve","isAbsolute","statSync","join","existsSync","accessSync","join","dirname","existsSync","dirname"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
computeCostDetail,
|
|
3
3
|
priceBasisOf
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-6DPOX5GU.js";
|
|
5
5
|
import {
|
|
6
6
|
allOf
|
|
7
7
|
} from "./chunk-OQB3XC5O.js";
|
|
@@ -22,20 +22,20 @@ import {
|
|
|
22
22
|
toolSuccess,
|
|
23
23
|
withProgressHeartbeat,
|
|
24
24
|
wrapToolWithTimeout
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-75J5CYUV.js";
|
|
26
26
|
import {
|
|
27
27
|
createEvent,
|
|
28
28
|
getGlobalRegistry
|
|
29
|
-
} from "./chunk-
|
|
29
|
+
} from "./chunk-CBFZSAUL.js";
|
|
30
30
|
import {
|
|
31
31
|
getToolMemory
|
|
32
|
-
} from "./chunk-
|
|
32
|
+
} from "./chunk-VP7KIRQQ.js";
|
|
33
33
|
import {
|
|
34
34
|
authRemediation,
|
|
35
35
|
delay,
|
|
36
36
|
getAvailableClis,
|
|
37
37
|
withTimeout
|
|
38
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-JUZRCQJI.js";
|
|
39
39
|
import {
|
|
40
40
|
AgentError,
|
|
41
41
|
CLI_NAMES,
|
|
@@ -64,16 +64,16 @@ import {
|
|
|
64
64
|
resolveClassGuardMs,
|
|
65
65
|
resolveModelIdentitySync,
|
|
66
66
|
resolveVoteTimeout
|
|
67
|
-
} from "./chunk-
|
|
67
|
+
} from "./chunk-BRPWBUSX.js";
|
|
68
68
|
import {
|
|
69
69
|
ensureLearningDir,
|
|
70
70
|
getOutcomesFile
|
|
71
|
-
} from "./chunk-
|
|
71
|
+
} from "./chunk-HHLCAWAV.js";
|
|
72
72
|
import {
|
|
73
73
|
getNexusDataDir,
|
|
74
74
|
nexusDataPath,
|
|
75
75
|
nexusDataPathEnsure
|
|
76
|
-
} from "./chunk-
|
|
76
|
+
} from "./chunk-NBMWONHE.js";
|
|
77
77
|
|
|
78
78
|
// src/mcp/tools/consensus-vote.ts
|
|
79
79
|
import { z as z10 } from "zod";
|
|
@@ -6162,7 +6162,7 @@ async function processVotesWithCascade(engineVotes, opts) {
|
|
|
6162
6162
|
var CONTRARIAN_ESCALATION_THRESHOLD = 0.8;
|
|
6163
6163
|
async function runContrarianCheck(proposal, log) {
|
|
6164
6164
|
try {
|
|
6165
|
-
const { executeExpert } = await import("./expert-bridge-
|
|
6165
|
+
const { executeExpert } = await import("./expert-bridge-FXGOGERJ.js");
|
|
6166
6166
|
const prompt = [
|
|
6167
6167
|
"You are a contrarian analyst. Your job is to find reasons this proposal should be REJECTED.",
|
|
6168
6168
|
"Look for: YAGNI (not needed), MISALIGNED (wrong tech/architecture), SECURITY_RISK, SCOPE_CREEP.",
|
|
@@ -6728,4 +6728,4 @@ export {
|
|
|
6728
6728
|
CONSENSUS_VOTE_TOOL_SCHEMA,
|
|
6729
6729
|
registerConsensusVoteTool
|
|
6730
6730
|
};
|
|
6731
|
-
//# sourceMappingURL=chunk-
|
|
6731
|
+
//# sourceMappingURL=chunk-QE3FY3DG.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
nexusDataPathEnsure
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-NBMWONHE.js";
|
|
4
4
|
|
|
5
5
|
// src/config/nexus-tmp-dir.ts
|
|
6
6
|
import { mkdirSync, mkdtempSync } from "fs";
|
|
@@ -36,4 +36,4 @@ export {
|
|
|
36
36
|
nexusMkdtempSync,
|
|
37
37
|
nexusMkdtemp
|
|
38
38
|
};
|
|
39
|
-
//# sourceMappingURL=chunk-
|
|
39
|
+
//# sourceMappingURL=chunk-RQV5ZUXT.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getRandomProvider,
|
|
3
3
|
getTimeProvider
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-BRPWBUSX.js";
|
|
5
5
|
|
|
6
6
|
// src/utils/id-utils.ts
|
|
7
7
|
import { randomUUID } from "crypto";
|
|
@@ -24,4 +24,4 @@ export {
|
|
|
24
24
|
generateHyphenId,
|
|
25
25
|
generateUUID
|
|
26
26
|
};
|
|
27
|
-
//# sourceMappingURL=chunk-
|
|
27
|
+
//# sourceMappingURL=chunk-TCKP3H54.js.map
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
TASK_CATEGORIES,
|
|
3
3
|
getAdaptiveBonus,
|
|
4
4
|
getOutcomeStore
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-BRPWBUSX.js";
|
|
6
6
|
|
|
7
7
|
// src/cli/doctor-deep.ts
|
|
8
8
|
var CLI_NAMES = ["claude", "gemini", "codex", "opencode"];
|
|
@@ -106,4 +106,4 @@ export {
|
|
|
106
106
|
runDeepDiagnostics,
|
|
107
107
|
formatDeepDiagnostics
|
|
108
108
|
};
|
|
109
|
-
//# sourceMappingURL=chunk-
|
|
109
|
+
//# sourceMappingURL=chunk-UCVDEZGK.js.map
|