nexus-agents 2.133.0 → 2.134.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.
Files changed (131) hide show
  1. package/dist/{child-mcp-config-R67B2KM6.js → child-mcp-config-TWHH63UK.js} +3 -3
  2. package/dist/{chunk-GYDO2WOR.js → chunk-33MFMXBQ.js} +5 -5
  3. package/dist/{chunk-VZCQRLXT.js → chunk-3EYXPV5F.js} +7 -7
  4. package/dist/{chunk-RLYXX3FQ.js → chunk-6LMZ7HFU.js} +2 -2
  5. package/dist/{chunk-4CLBJ2NA.js → chunk-6UCWR3DS.js} +3 -3
  6. package/dist/{chunk-RJEP2AZW.js → chunk-76R5ES6Z.js} +36 -36
  7. package/dist/{chunk-RJEP2AZW.js.map → chunk-76R5ES6Z.js.map} +1 -1
  8. package/dist/{chunk-HGUO36KW.js → chunk-7GSYICTL.js} +8 -8
  9. package/dist/{chunk-ZVBGZBW5.js → chunk-7TQZR5VU.js} +114 -7
  10. package/dist/chunk-7TQZR5VU.js.map +1 -0
  11. package/dist/{chunk-2CLFX73Y.js → chunk-B26FGLIJ.js} +2 -2
  12. package/dist/{chunk-27DRQWON.js → chunk-BTYYZ6VU.js} +4 -4
  13. package/dist/{chunk-K5WBFAR4.js → chunk-CLRSNWRQ.js} +4 -4
  14. package/dist/{chunk-TGGR6ST5.js → chunk-COJOUIO2.js} +3 -3
  15. package/dist/{chunk-QJIHSQZX.js → chunk-DBDWMHUL.js} +65 -14
  16. package/dist/chunk-DBDWMHUL.js.map +1 -0
  17. package/dist/{chunk-4CVITS5D.js → chunk-DLUFDKPA.js} +9 -9
  18. package/dist/{chunk-PM63X3QG.js → chunk-E64SZTEP.js} +3 -3
  19. package/dist/{chunk-QMCHVYZB.js → chunk-EHLJLIHS.js} +2 -2
  20. package/dist/{chunk-ZTRBMKXK.js → chunk-F74ZGHAP.js} +2 -2
  21. package/dist/{chunk-NZGNOXXW.js → chunk-FPMQ2JAK.js} +2 -2
  22. package/dist/{chunk-4DLHM6LI.js → chunk-FSFF7EFR.js} +2 -2
  23. package/dist/{chunk-J435FU54.js → chunk-FUJ3XR7T.js} +4 -4
  24. package/dist/{chunk-CI5KGCX5.js → chunk-FVSZLVMR.js} +3 -3
  25. package/dist/{chunk-RUSP5PJR.js → chunk-GZ4NF4ZW.js} +5 -1
  26. package/dist/{chunk-RUSP5PJR.js.map → chunk-GZ4NF4ZW.js.map} +1 -1
  27. package/dist/{chunk-DETYVPZO.js → chunk-IWQH6TP7.js} +6 -6
  28. package/dist/{chunk-ZQEQVCIU.js → chunk-MY52DFXC.js} +2 -2
  29. package/dist/{chunk-FKTLAPXJ.js → chunk-OCKZ6F5O.js} +3 -3
  30. package/dist/{chunk-E4IYX7LD.js → chunk-ORQAFTAZ.js} +2 -2
  31. package/dist/{chunk-QLRH6KOT.js → chunk-OU2NQVKD.js} +2 -2
  32. package/dist/{chunk-7BONPRR2.js → chunk-PFBV5FCT.js} +2 -2
  33. package/dist/{chunk-S4U3Z6ZS.js → chunk-QZUT22LP.js} +6 -6
  34. package/dist/{chunk-EFDXX5MC.js → chunk-UDB5NHJI.js} +3 -3
  35. package/dist/{chunk-RAWF4JOT.js → chunk-VI7LELES.js} +7 -7
  36. package/dist/{chunk-ECDJM6UB.js → chunk-WFKVUZ3O.js} +2 -2
  37. package/dist/{chunk-XIFOAZ5B.js → chunk-WYJJUF6N.js} +4 -4
  38. package/dist/{chunk-GET2MTLW.js → chunk-Z6DXZ6AS.js} +2 -2
  39. package/dist/{chunk-WHZD2W6Q.js → chunk-ZMDOGN33.js} +2 -2
  40. package/dist/{cli-circuit-breaker-J6UFONNE.js → cli-circuit-breaker-VXBDCAD7.js} +5 -5
  41. package/dist/cli.js +844 -155
  42. package/dist/cli.js.map +1 -1
  43. package/dist/{composite-router-HQUSCJO4.js → composite-router-E6FXXMMR.js} +3 -3
  44. package/dist/{consensus-vote-MVZ27Y43.js → consensus-vote-R6X5IL57.js} +15 -15
  45. package/dist/{context-retriever-5OVRAWNZ.js → context-retriever-I4NEOUEV.js} +9 -9
  46. package/dist/{doctor-deep-HJ3NQ365.js → doctor-deep-CZXN4YD6.js} +4 -4
  47. package/dist/{expert-bridge-MINXBC73.js → expert-bridge-GMB5IHHF.js} +5 -5
  48. package/dist/factory-WR62MEIJ.js +14 -0
  49. package/dist/factory-ZBQGA373.js +21 -0
  50. package/dist/{improvement-review-ZL3364R2.js → improvement-review-77BKIQGN.js} +5 -5
  51. package/dist/index.d.ts +210 -192
  52. package/dist/index.js +30 -30
  53. package/dist/{init-opencode-L3NT524E.js → init-opencode-4H2VPN23.js} +7 -7
  54. package/dist/issue-triage-NJB6SL4S.js +16 -0
  55. package/dist/{learning-persistence-QFCQ5POD.js → learning-persistence-2KO4CXNL.js} +2 -2
  56. package/dist/{pr-reviewer-helpers-PLKDVWYF.js → pr-reviewer-helpers-F3SHCHNV.js} +5 -5
  57. package/dist/{registry-command-HPKNLYUL.js → registry-command-VFCSMHME.js} +3 -3
  58. package/dist/{repo-security-plan-HSYGGVEJ.js → repo-security-plan-U2ZIFW53.js} +4 -4
  59. package/dist/research-helpers-synthesize-5TLNHT3I.js +14 -0
  60. package/dist/{routing-memory-OGUOL7UF.js → routing-memory-VVLJL3MG.js} +3 -3
  61. package/dist/{session-memory-HQWAXH3C.js → session-memory-GMQYZLJE.js} +4 -4
  62. package/dist/{setup-command-CIXJXFPC.js → setup-command-IMAX6EAO.js} +12 -12
  63. package/dist/setup-config-2ZSJ3HNE.js +10 -0
  64. package/dist/{setup-custom-api-W7EDVKWR.js → setup-custom-api-NJGCRIRO.js} +4 -4
  65. package/dist/{tool-memory-Z2B7CAH7.js → tool-memory-TSYJXGOV.js} +6 -6
  66. package/dist/unified-registry-IMAL3SY6.js +24 -0
  67. package/dist/{weather-report-GX7OIUL2.js → weather-report-OU65NJS3.js} +3 -3
  68. package/package.json +1 -1
  69. package/dist/chunk-QJIHSQZX.js.map +0 -1
  70. package/dist/chunk-ZVBGZBW5.js.map +0 -1
  71. package/dist/factory-KC7BYHAP.js +0 -21
  72. package/dist/factory-ZG2FZYVA.js +0 -14
  73. package/dist/issue-triage-CZPFNGB7.js +0 -16
  74. package/dist/research-helpers-synthesize-IQHDU27S.js +0 -14
  75. package/dist/setup-config-HYX3BRSE.js +0 -10
  76. package/dist/unified-registry-UFNSWKZA.js +0 -24
  77. /package/dist/{child-mcp-config-R67B2KM6.js.map → child-mcp-config-TWHH63UK.js.map} +0 -0
  78. /package/dist/{chunk-GYDO2WOR.js.map → chunk-33MFMXBQ.js.map} +0 -0
  79. /package/dist/{chunk-VZCQRLXT.js.map → chunk-3EYXPV5F.js.map} +0 -0
  80. /package/dist/{chunk-RLYXX3FQ.js.map → chunk-6LMZ7HFU.js.map} +0 -0
  81. /package/dist/{chunk-4CLBJ2NA.js.map → chunk-6UCWR3DS.js.map} +0 -0
  82. /package/dist/{chunk-HGUO36KW.js.map → chunk-7GSYICTL.js.map} +0 -0
  83. /package/dist/{chunk-2CLFX73Y.js.map → chunk-B26FGLIJ.js.map} +0 -0
  84. /package/dist/{chunk-27DRQWON.js.map → chunk-BTYYZ6VU.js.map} +0 -0
  85. /package/dist/{chunk-K5WBFAR4.js.map → chunk-CLRSNWRQ.js.map} +0 -0
  86. /package/dist/{chunk-TGGR6ST5.js.map → chunk-COJOUIO2.js.map} +0 -0
  87. /package/dist/{chunk-4CVITS5D.js.map → chunk-DLUFDKPA.js.map} +0 -0
  88. /package/dist/{chunk-PM63X3QG.js.map → chunk-E64SZTEP.js.map} +0 -0
  89. /package/dist/{chunk-QMCHVYZB.js.map → chunk-EHLJLIHS.js.map} +0 -0
  90. /package/dist/{chunk-ZTRBMKXK.js.map → chunk-F74ZGHAP.js.map} +0 -0
  91. /package/dist/{chunk-NZGNOXXW.js.map → chunk-FPMQ2JAK.js.map} +0 -0
  92. /package/dist/{chunk-4DLHM6LI.js.map → chunk-FSFF7EFR.js.map} +0 -0
  93. /package/dist/{chunk-J435FU54.js.map → chunk-FUJ3XR7T.js.map} +0 -0
  94. /package/dist/{chunk-CI5KGCX5.js.map → chunk-FVSZLVMR.js.map} +0 -0
  95. /package/dist/{chunk-DETYVPZO.js.map → chunk-IWQH6TP7.js.map} +0 -0
  96. /package/dist/{chunk-ZQEQVCIU.js.map → chunk-MY52DFXC.js.map} +0 -0
  97. /package/dist/{chunk-FKTLAPXJ.js.map → chunk-OCKZ6F5O.js.map} +0 -0
  98. /package/dist/{chunk-E4IYX7LD.js.map → chunk-ORQAFTAZ.js.map} +0 -0
  99. /package/dist/{chunk-QLRH6KOT.js.map → chunk-OU2NQVKD.js.map} +0 -0
  100. /package/dist/{chunk-7BONPRR2.js.map → chunk-PFBV5FCT.js.map} +0 -0
  101. /package/dist/{chunk-S4U3Z6ZS.js.map → chunk-QZUT22LP.js.map} +0 -0
  102. /package/dist/{chunk-EFDXX5MC.js.map → chunk-UDB5NHJI.js.map} +0 -0
  103. /package/dist/{chunk-RAWF4JOT.js.map → chunk-VI7LELES.js.map} +0 -0
  104. /package/dist/{chunk-ECDJM6UB.js.map → chunk-WFKVUZ3O.js.map} +0 -0
  105. /package/dist/{chunk-XIFOAZ5B.js.map → chunk-WYJJUF6N.js.map} +0 -0
  106. /package/dist/{chunk-GET2MTLW.js.map → chunk-Z6DXZ6AS.js.map} +0 -0
  107. /package/dist/{chunk-WHZD2W6Q.js.map → chunk-ZMDOGN33.js.map} +0 -0
  108. /package/dist/{cli-circuit-breaker-J6UFONNE.js.map → cli-circuit-breaker-VXBDCAD7.js.map} +0 -0
  109. /package/dist/{composite-router-HQUSCJO4.js.map → composite-router-E6FXXMMR.js.map} +0 -0
  110. /package/dist/{consensus-vote-MVZ27Y43.js.map → consensus-vote-R6X5IL57.js.map} +0 -0
  111. /package/dist/{context-retriever-5OVRAWNZ.js.map → context-retriever-I4NEOUEV.js.map} +0 -0
  112. /package/dist/{doctor-deep-HJ3NQ365.js.map → doctor-deep-CZXN4YD6.js.map} +0 -0
  113. /package/dist/{expert-bridge-MINXBC73.js.map → expert-bridge-GMB5IHHF.js.map} +0 -0
  114. /package/dist/{factory-KC7BYHAP.js.map → factory-WR62MEIJ.js.map} +0 -0
  115. /package/dist/{factory-ZG2FZYVA.js.map → factory-ZBQGA373.js.map} +0 -0
  116. /package/dist/{improvement-review-ZL3364R2.js.map → improvement-review-77BKIQGN.js.map} +0 -0
  117. /package/dist/{init-opencode-L3NT524E.js.map → init-opencode-4H2VPN23.js.map} +0 -0
  118. /package/dist/{issue-triage-CZPFNGB7.js.map → issue-triage-NJB6SL4S.js.map} +0 -0
  119. /package/dist/{learning-persistence-QFCQ5POD.js.map → learning-persistence-2KO4CXNL.js.map} +0 -0
  120. /package/dist/{pr-reviewer-helpers-PLKDVWYF.js.map → pr-reviewer-helpers-F3SHCHNV.js.map} +0 -0
  121. /package/dist/{registry-command-HPKNLYUL.js.map → registry-command-VFCSMHME.js.map} +0 -0
  122. /package/dist/{repo-security-plan-HSYGGVEJ.js.map → repo-security-plan-U2ZIFW53.js.map} +0 -0
  123. /package/dist/{research-helpers-synthesize-IQHDU27S.js.map → research-helpers-synthesize-5TLNHT3I.js.map} +0 -0
  124. /package/dist/{routing-memory-OGUOL7UF.js.map → routing-memory-VVLJL3MG.js.map} +0 -0
  125. /package/dist/{session-memory-HQWAXH3C.js.map → session-memory-GMQYZLJE.js.map} +0 -0
  126. /package/dist/{setup-command-CIXJXFPC.js.map → setup-command-IMAX6EAO.js.map} +0 -0
  127. /package/dist/{setup-config-HYX3BRSE.js.map → setup-config-2ZSJ3HNE.js.map} +0 -0
  128. /package/dist/{setup-custom-api-W7EDVKWR.js.map → setup-custom-api-NJGCRIRO.js.map} +0 -0
  129. /package/dist/{tool-memory-Z2B7CAH7.js.map → tool-memory-TSYJXGOV.js.map} +0 -0
  130. /package/dist/{unified-registry-UFNSWKZA.js.map → unified-registry-IMAL3SY6.js.map} +0 -0
  131. /package/dist/{weather-report-GX7OIUL2.js.map → weather-report-OU65NJS3.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  computeCostUSD
3
- } from "./chunk-TGGR6ST5.js";
3
+ } from "./chunk-COJOUIO2.js";
4
4
  import {
5
5
  DEFAULT_CONSENSUS_CONFIG,
6
6
  DEFAULT_INCREMENTAL_QUORUM_CONFIG,
@@ -18,20 +18,20 @@ import {
18
18
  toolSuccess,
19
19
  withProgressHeartbeat,
20
20
  wrapToolWithTimeout
21
- } from "./chunk-4CLBJ2NA.js";
21
+ } from "./chunk-6UCWR3DS.js";
22
22
  import {
23
23
  getToolMemory
24
- } from "./chunk-GYDO2WOR.js";
24
+ } from "./chunk-33MFMXBQ.js";
25
25
  import {
26
26
  createEvent,
27
27
  getGlobalRegistry
28
- } from "./chunk-XIFOAZ5B.js";
28
+ } from "./chunk-WYJJUF6N.js";
29
29
  import {
30
30
  authRemediation,
31
31
  delay,
32
32
  getAvailableClis,
33
33
  withTimeout
34
- } from "./chunk-VZCQRLXT.js";
34
+ } from "./chunk-3EYXPV5F.js";
35
35
  import {
36
36
  AgentError,
37
37
  CLI_NAMES,
@@ -58,14 +58,14 @@ import {
58
58
  registerPersistentOutcomeStoreFactory,
59
59
  resolveClassGuardMs,
60
60
  resolveVoteTimeout
61
- } from "./chunk-QJIHSQZX.js";
61
+ } from "./chunk-DBDWMHUL.js";
62
62
  import {
63
63
  ensureLearningDir,
64
64
  findRepoRoot,
65
65
  getOutcomesFile,
66
66
  nexusDataPath,
67
67
  nexusDataPathEnsure
68
- } from "./chunk-RUSP5PJR.js";
68
+ } from "./chunk-GZ4NF4ZW.js";
69
69
 
70
70
  // src/mcp/tools/consensus-vote.ts
71
71
  import { z as z10 } from "zod";
@@ -5501,7 +5501,7 @@ async function processVotesWithCascade(engineVotes, opts) {
5501
5501
  var CONTRARIAN_ESCALATION_THRESHOLD = 0.8;
5502
5502
  async function runContrarianCheck(proposal, log) {
5503
5503
  try {
5504
- const { executeExpert } = await import("./expert-bridge-MINXBC73.js");
5504
+ const { executeExpert } = await import("./expert-bridge-GMB5IHHF.js");
5505
5505
  const prompt = [
5506
5506
  "You are a contrarian analyst. Your job is to find reasons this proposal should be REJECTED.",
5507
5507
  "Look for: YAGNI (not needed), MISALIGNED (wrong tech/architecture), SECURITY_RISK, SCOPE_CREEP.",
@@ -5941,4 +5941,4 @@ export {
5941
5941
  CONSENSUS_VOTE_OUTPUT_SCHEMA,
5942
5942
  registerConsensusVoteTool
5943
5943
  };
5944
- //# sourceMappingURL=chunk-4CVITS5D.js.map
5944
+ //# sourceMappingURL=chunk-DLUFDKPA.js.map
@@ -3,14 +3,14 @@ import {
3
3
  createStream,
4
4
  requireApiKey,
5
5
  validateApiKeyPresence
6
- } from "./chunk-ECDJM6UB.js";
6
+ } from "./chunk-WFKVUZ3O.js";
7
7
  import {
8
8
  ModelCapability,
9
9
  err,
10
10
  getCliModelName,
11
11
  getTokenEstimator,
12
12
  ok
13
- } from "./chunk-QJIHSQZX.js";
13
+ } from "./chunk-DBDWMHUL.js";
14
14
 
15
15
  // src/adapters/openai-types.ts
16
16
  var OPENAI_MODELS = {
@@ -553,4 +553,4 @@ export {
553
553
  OpenAIAdapter,
554
554
  createOpenAIAdapter
555
555
  };
556
- //# sourceMappingURL=chunk-PM63X3QG.js.map
556
+ //# sourceMappingURL=chunk-E64SZTEP.js.map
@@ -2,7 +2,7 @@ import {
2
2
  CACHE_TIMEOUTS,
3
3
  createLogger,
4
4
  getTimeProvider
5
- } from "./chunk-QJIHSQZX.js";
5
+ } from "./chunk-DBDWMHUL.js";
6
6
 
7
7
  // src/security/trust-types.ts
8
8
  import { z } from "zod";
@@ -560,4 +560,4 @@ export {
560
560
  resolveReputationGatingMode,
561
561
  gateWithReputation
562
562
  };
563
- //# sourceMappingURL=chunk-QMCHVYZB.js.map
563
+ //# sourceMappingURL=chunk-EHLJLIHS.js.map
@@ -5,7 +5,7 @@ import {
5
5
  getErrorMessage,
6
6
  getTimeProvider,
7
7
  ok
8
- } from "./chunk-QJIHSQZX.js";
8
+ } from "./chunk-DBDWMHUL.js";
9
9
 
10
10
  // src/cli-adapters/circuit-breaker-types.ts
11
11
  var CircuitErrorCode = {
@@ -375,4 +375,4 @@ export {
375
375
  mapCliErrorToCategory,
376
376
  mapModelErrorToCategory
377
377
  };
378
- //# sourceMappingURL=chunk-ZTRBMKXK.js.map
378
+ //# sourceMappingURL=chunk-F74ZGHAP.js.map
@@ -4,7 +4,7 @@ import {
4
4
  getErrorMessage,
5
5
  getTimeProvider,
6
6
  ok
7
- } from "./chunk-QJIHSQZX.js";
7
+ } from "./chunk-DBDWMHUL.js";
8
8
 
9
9
  // src/context/session-memory.ts
10
10
  import * as fs from "fs";
@@ -352,4 +352,4 @@ export {
352
352
  SessionMemory,
353
353
  createSessionMemory
354
354
  };
355
- //# sourceMappingURL=chunk-NZGNOXXW.js.map
355
+ //# sourceMappingURL=chunk-FPMQ2JAK.js.map
@@ -4,7 +4,7 @@ import {
4
4
  err,
5
5
  getErrorMessage,
6
6
  ok
7
- } from "./chunk-QJIHSQZX.js";
7
+ } from "./chunk-DBDWMHUL.js";
8
8
 
9
9
  // src/scm/types.ts
10
10
  var ScmError = class extends Error {
@@ -263,4 +263,4 @@ export {
263
263
  ScmError,
264
264
  GitHubProvider
265
265
  };
266
- //# sourceMappingURL=chunk-4DLHM6LI.js.map
266
+ //# sourceMappingURL=chunk-FSFF7EFR.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  GitHubProvider,
3
3
  ScmError
4
- } from "./chunk-4DLHM6LI.js";
4
+ } from "./chunk-FSFF7EFR.js";
5
5
  import {
6
6
  ROLE_DEFAULT_TRUST,
7
7
  ReputationCache,
@@ -11,14 +11,14 @@ import {
11
11
  gateWithReputation,
12
12
  resolveReputationGatingMode,
13
13
  sanitizeInput
14
- } from "./chunk-QMCHVYZB.js";
14
+ } from "./chunk-EHLJLIHS.js";
15
15
  import {
16
16
  CLI_SUBPROCESS_TIMEOUTS,
17
17
  createLogger,
18
18
  err,
19
19
  getTimeProvider,
20
20
  ok
21
- } from "./chunk-QJIHSQZX.js";
21
+ } from "./chunk-DBDWMHUL.js";
22
22
 
23
23
  // src/security/trust-classifier.ts
24
24
  function mapAuthorAssociation(association) {
@@ -1401,4 +1401,4 @@ export {
1401
1401
  IssueTriage,
1402
1402
  createIssueTriage
1403
1403
  };
1404
- //# sourceMappingURL=chunk-J435FU54.js.map
1404
+ //# sourceMappingURL=chunk-FUJ3XR7T.js.map
@@ -2,14 +2,14 @@ import {
2
2
  CircuitBreakerRegistry,
3
3
  CircuitError,
4
4
  mapCliErrorToCategory
5
- } from "./chunk-ZTRBMKXK.js";
5
+ } from "./chunk-F74ZGHAP.js";
6
6
  import {
7
7
  createLogger,
8
8
  err,
9
9
  getFallbackChainForCategory,
10
10
  getTimeProvider,
11
11
  ok
12
- } from "./chunk-QJIHSQZX.js";
12
+ } from "./chunk-DBDWMHUL.js";
13
13
 
14
14
  // src/cli-adapters/cli-circuit-breaker.ts
15
15
  var CATEGORY_TO_FALLBACK = {
@@ -152,4 +152,4 @@ export {
152
152
  CliCircuitBreakerIntegration,
153
153
  createCliCircuitBreakerIntegration
154
154
  };
155
- //# sourceMappingURL=chunk-CI5KGCX5.js.map
155
+ //# sourceMappingURL=chunk-FVSZLVMR.js.map
@@ -299,6 +299,9 @@ function nexusDataPathEnsure(...segments) {
299
299
  mkdirSync(target, { recursive: true });
300
300
  return resolved;
301
301
  }
302
+ function nexusSharedPath(...segments) {
303
+ return join2(getNexusDataDir(), ...segments);
304
+ }
302
305
  function getPerRepoSubdirs() {
303
306
  return PER_REPO_SUBDIRS;
304
307
  }
@@ -370,6 +373,7 @@ export {
370
373
  getNexusRepoDir,
371
374
  nexusDataPath,
372
375
  nexusDataPathEnsure,
376
+ nexusSharedPath,
373
377
  getPerRepoSubdirs,
374
378
  sessionsDbPath,
375
379
  getLearningDir,
@@ -381,4 +385,4 @@ export {
381
385
  isPersistenceEnabled,
382
386
  ensureLearningDir
383
387
  };
384
- //# sourceMappingURL=chunk-RUSP5PJR.js.map
388
+ //# sourceMappingURL=chunk-GZ4NF4ZW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config/learning-persistence.ts","../src/config/nexus-data-dir.ts","../src/config/sandbox-detection.ts","../src/config/repo-root-detection.ts","../src/config/portable-mode.ts"],"sourcesContent":["/**\n * Shared configuration for cross-session learning persistence.\n *\n * Controls where learning data (outcomes, distilled rules) is stored\n * on disk and whether persistence is enabled via feature flag.\n *\n * @module config/learning-persistence\n * (Source: Issue #1009 — Cross-session persistence)\n */\n\nimport { mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getNexusDataDir } from './nexus-data-dir.js';\n\n// ============================================================================\n// Path resolution (#2316: must read NEXUS_DATA_DIR at call time, not import)\n// ============================================================================\n\n/**\n * Base directory for learning persistence data. Resolved at call time so\n * `NEXUS_DATA_DIR` overrides take effect — the const-at-import-time\n * pattern this replaces was the bug discovered while dogfooding v2.63.0\n * (#2316). Outcome counts on a fresh portable workspace were leaking\n * the host home directory's outcome history.\n */\nexport function getLearningDir(): string {\n return join(getNexusDataDir(), 'learning');\n}\n\n/** JSONL file for persisted task outcomes. */\nexport function getOutcomesFile(): string {\n return join(getLearningDir(), 'outcomes.jsonl');\n}\n\n/** JSON file for persisted distilled rules. */\nexport function getRulesFile(): string {\n return join(getLearningDir(), 'rules.json');\n}\n\n/**\n * JSONL file for per-voter pr_review eval verdicts (#3848).\n *\n * Stores ONLY rubric-scored per-voter TP/FP/FN tallies vs ground truth — never\n * raw diffs, prompts, or model outputs. Lets per-voter precision/recall accrue\n * across runs so a chronically-noisy-voter demotion (Epic D / ADR-0017) has\n * citable evidence.\n */\nexport function getPrReviewEvalFile(): string {\n return join(getLearningDir(), 'pr-review-eval.jsonl');\n}\n\n/**\n * JSONL file for per-decision cost rollups (#3855).\n *\n * Stores ONLY the per-decision cost summary (per-voter / per-model token + USD\n * totals) for a governed `consensus_vote` / `pr_review` run — never raw\n * proposals, diffs, prompts, or model outputs. Lets \"what did this governed\n * decision cost?\" be answered from recorded data (epic #3854; feeds Epic G's\n * weather_report + manifest cost profiles in #3856).\n */\nexport function getDecisionCostFile(): string {\n return join(getLearningDir(), 'decision-costs.jsonl');\n}\n\n/**\n * JSONL file for the MetaOrchestrator shadow selector's training outcomes\n * (#3593). Stores ONLY numeric/categorical bandit-feature values + a boolean\n * success flag — never raw task text. Lets the shadow selector learn across\n * processes by replaying past outcomes on construction.\n */\nexport function getMetaOutcomesFile(): string {\n return join(getLearningDir(), 'meta-outcomes.jsonl');\n}\n\n// Note: previous LEARNING_DIR / OUTCOMES_FILE / RULES_FILE exports were\n// removed in #2316 — they were evaluated at module import time and ignored\n// `NEXUS_DATA_DIR`. All callers must use the getter functions above.\n\n/** Directory mode: owner-only (rwx------). */\nconst DIR_MODE = 0o700;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Check whether learning persistence is enabled via feature flag.\n *\n * Defaults to true — cross-session LinUCB routing data persists to\n * `~/.nexus-agents/learning/` unless explicitly disabled.\n * Only routing metadata is stored (model, success, duration, category).\n * No user prompts, API keys, or model outputs are persisted.\n *\n * Set NEXUS_PERSIST_LEARNING=false to disable.\n */\nexport function isPersistenceEnabled(): boolean {\n return process.env['NEXUS_PERSIST_LEARNING'] !== 'false';\n}\n\n/** Ensure the learning data directory exists. */\nexport function ensureLearningDir(dir?: string): void {\n mkdirSync(dir ?? getLearningDir(), { recursive: true, mode: DIR_MODE });\n}\n","/**\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 `findRepoRoot(cwd)` succeeds AND\n * `NEXUS_REPO_PREFERRED` is not explicitly `'0'`):\n * `<repo-root>/.nexus-agents/<subdir>/`. Auto-adds `.nexus-agents/`\n * to 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 renameSync,\n unlinkSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, 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 '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]);\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 * 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\n * `findRepoRoot(cwd)` finds an ancestor `.git`.\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 const root = 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":";AAUA,SAAS,aAAAA,kBAAiB;AAC1B,SAAS,QAAAC,aAAY;;;ACmCrB;AAAA,EACE,cAAAC;AAAA,EACA,aAAa;AAAA,EACb;AAAA,EACA,cAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAAC,gBAAe;AACxB,SAAS,WAAAC,UAAS,QAAAC,OAAM,WAAAC,gBAAe;;;AChCvC,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;AAC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AO,QAAQ,IAAI,wBAAwB,MAAM;AACnD;AAGO,SAAS,kBAAkB,KAAoB;AACpD,EAAAC,WAAU,OAAO,eAAe,GAAG,EAAE,WAAW,MAAM,MAAM,SAAS,CAAC;AACxE;","names":["mkdirSync","join","accessSync","existsSync","homedir","dirname","join","resolve","existsSync","readFileSync","existsSync","readFileSync","statSync","resolve","resolve","join","homedir","join","existsSync","accessSync","join","dirname","existsSync","dirname","join","mkdirSync"]}
1
+ {"version":3,"sources":["../src/config/learning-persistence.ts","../src/config/nexus-data-dir.ts","../src/config/sandbox-detection.ts","../src/config/repo-root-detection.ts","../src/config/portable-mode.ts"],"sourcesContent":["/**\n * Shared configuration for cross-session learning persistence.\n *\n * Controls where learning data (outcomes, distilled rules) is stored\n * on disk and whether persistence is enabled via feature flag.\n *\n * @module config/learning-persistence\n * (Source: Issue #1009 — Cross-session persistence)\n */\n\nimport { mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { getNexusDataDir } from './nexus-data-dir.js';\n\n// ============================================================================\n// Path resolution (#2316: must read NEXUS_DATA_DIR at call time, not import)\n// ============================================================================\n\n/**\n * Base directory for learning persistence data. Resolved at call time so\n * `NEXUS_DATA_DIR` overrides take effect — the const-at-import-time\n * pattern this replaces was the bug discovered while dogfooding v2.63.0\n * (#2316). Outcome counts on a fresh portable workspace were leaking\n * the host home directory's outcome history.\n */\nexport function getLearningDir(): string {\n return join(getNexusDataDir(), 'learning');\n}\n\n/** JSONL file for persisted task outcomes. */\nexport function getOutcomesFile(): string {\n return join(getLearningDir(), 'outcomes.jsonl');\n}\n\n/** JSON file for persisted distilled rules. */\nexport function getRulesFile(): string {\n return join(getLearningDir(), 'rules.json');\n}\n\n/**\n * JSONL file for per-voter pr_review eval verdicts (#3848).\n *\n * Stores ONLY rubric-scored per-voter TP/FP/FN tallies vs ground truth — never\n * raw diffs, prompts, or model outputs. Lets per-voter precision/recall accrue\n * across runs so a chronically-noisy-voter demotion (Epic D / ADR-0017) has\n * citable evidence.\n */\nexport function getPrReviewEvalFile(): string {\n return join(getLearningDir(), 'pr-review-eval.jsonl');\n}\n\n/**\n * JSONL file for per-decision cost rollups (#3855).\n *\n * Stores ONLY the per-decision cost summary (per-voter / per-model token + USD\n * totals) for a governed `consensus_vote` / `pr_review` run — never raw\n * proposals, diffs, prompts, or model outputs. Lets \"what did this governed\n * decision cost?\" be answered from recorded data (epic #3854; feeds Epic G's\n * weather_report + manifest cost profiles in #3856).\n */\nexport function getDecisionCostFile(): string {\n return join(getLearningDir(), 'decision-costs.jsonl');\n}\n\n/**\n * JSONL file for the MetaOrchestrator shadow selector's training outcomes\n * (#3593). Stores ONLY numeric/categorical bandit-feature values + a boolean\n * success flag — never raw task text. Lets the shadow selector learn across\n * processes by replaying past outcomes on construction.\n */\nexport function getMetaOutcomesFile(): string {\n return join(getLearningDir(), 'meta-outcomes.jsonl');\n}\n\n// Note: previous LEARNING_DIR / OUTCOMES_FILE / RULES_FILE exports were\n// removed in #2316 — they were evaluated at module import time and ignored\n// `NEXUS_DATA_DIR`. All callers must use the getter functions above.\n\n/** Directory mode: owner-only (rwx------). */\nconst DIR_MODE = 0o700;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Check whether learning persistence is enabled via feature flag.\n *\n * Defaults to true — cross-session LinUCB routing data persists to\n * `~/.nexus-agents/learning/` unless explicitly disabled.\n * Only routing metadata is stored (model, success, duration, category).\n * No user prompts, API keys, or model outputs are persisted.\n *\n * Set NEXUS_PERSIST_LEARNING=false to disable.\n */\nexport function isPersistenceEnabled(): boolean {\n return process.env['NEXUS_PERSIST_LEARNING'] !== 'false';\n}\n\n/** Ensure the learning data directory exists. */\nexport function ensureLearningDir(dir?: string): void {\n mkdirSync(dir ?? getLearningDir(), { recursive: true, mode: DIR_MODE });\n}\n","/**\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 `findRepoRoot(cwd)` succeeds AND\n * `NEXUS_REPO_PREFERRED` is not explicitly `'0'`):\n * `<repo-root>/.nexus-agents/<subdir>/`. Auto-adds `.nexus-agents/`\n * to 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 renameSync,\n unlinkSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, 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 '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]);\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 * 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\n * `findRepoRoot(cwd)` finds an ancestor `.git`.\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 const root = 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":";AAUA,SAAS,aAAAA,kBAAiB;AAC1B,SAAS,QAAAC,aAAY;;;ACmCrB;AAAA,EACE,cAAAC;AAAA,EACA,aAAa;AAAA,EACb;AAAA,EACA,cAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAAC,gBAAe;AACxB,SAAS,WAAAC,UAAS,QAAAC,OAAM,WAAAC,gBAAe;;;AChCvC,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;AACh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,gBAAgB;AAChD;AAGO,SAAS,eAAuB;AACrC,SAAOA,MAAK,eAAe,GAAG,YAAY;AAC5C;AAUO,SAAS,sBAA8B;AAC5C,SAAOA,MAAK,eAAe,GAAG,sBAAsB;AACtD;AAWO,SAAS,sBAA8B;AAC5C,SAAOA,MAAK,eAAe,GAAG,sBAAsB;AACtD;AAQO,SAAS,sBAA8B;AAC5C,SAAOA,MAAK,eAAe,GAAG,qBAAqB;AACrD;AAOA,IAAM,WAAW;AAgBV,SAAS,uBAAgC;AAC9C,SAAO,QAAQ,IAAI,wBAAwB,MAAM;AACnD;AAGO,SAAS,kBAAkB,KAAoB;AACpD,EAAAC,WAAU,OAAO,eAAe,GAAG,EAAE,WAAW,MAAM,MAAM,SAAS,CAAC;AACxE;","names":["mkdirSync","join","accessSync","existsSync","homedir","dirname","join","resolve","existsSync","readFileSync","existsSync","readFileSync","statSync","resolve","resolve","join","homedir","join","existsSync","accessSync","join","dirname","existsSync","dirname","join","mkdirSync"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runConfigInitSync
3
- } from "./chunk-QLRH6KOT.js";
3
+ } from "./chunk-OU2NQVKD.js";
4
4
  import {
5
5
  VERSION,
6
6
  checkApiKeys,
@@ -8,13 +8,13 @@ import {
8
8
  checkSqlite,
9
9
  defaultConfig,
10
10
  initDataDirectories
11
- } from "./chunk-HGUO36KW.js";
11
+ } from "./chunk-7GSYICTL.js";
12
12
  import {
13
13
  BUILT_IN_EXPERTS
14
14
  } from "./chunk-ZM4O442V.js";
15
15
  import {
16
16
  probeAllClis
17
- } from "./chunk-VZCQRLXT.js";
17
+ } from "./chunk-3EYXPV5F.js";
18
18
  import {
19
19
  CLI_SUBPROCESS_TIMEOUTS,
20
20
  colors,
@@ -25,11 +25,11 @@ import {
25
25
  getErrorMessage,
26
26
  getTimeProvider,
27
27
  symbols
28
- } from "./chunk-QJIHSQZX.js";
28
+ } from "./chunk-DBDWMHUL.js";
29
29
  import {
30
30
  ensureGitignored,
31
31
  findRepoRoot
32
- } from "./chunk-RUSP5PJR.js";
32
+ } from "./chunk-GZ4NF4ZW.js";
33
33
 
34
34
  // src/cli/setup-command.ts
35
35
  import { existsSync as existsSync4 } from "fs";
@@ -2000,4 +2000,4 @@ export {
2000
2000
  setupCommand,
2001
2001
  setupCommandAsync
2002
2002
  };
2003
- //# sourceMappingURL=chunk-DETYVPZO.js.map
2003
+ //# sourceMappingURL=chunk-IWQH6TP7.js.map
@@ -2,7 +2,7 @@ import {
2
2
  createLogger,
3
3
  err,
4
4
  ok
5
- } from "./chunk-QJIHSQZX.js";
5
+ } from "./chunk-DBDWMHUL.js";
6
6
 
7
7
  // src/scm/token-resolver.ts
8
8
  import { execFile } from "child_process";
@@ -87,4 +87,4 @@ export {
87
87
  hasToken,
88
88
  getTokenEnvVars
89
89
  };
90
- //# sourceMappingURL=chunk-ZQEQVCIU.js.map
90
+ //# sourceMappingURL=chunk-MY52DFXC.js.map
@@ -9,11 +9,11 @@ import {
9
9
  gateWithReputation,
10
10
  resolveReputationGatingMode,
11
11
  sanitizeInput
12
- } from "./chunk-QMCHVYZB.js";
12
+ } from "./chunk-EHLJLIHS.js";
13
13
  import {
14
14
  createLogger,
15
15
  getTimeProvider
16
- } from "./chunk-QJIHSQZX.js";
16
+ } from "./chunk-DBDWMHUL.js";
17
17
 
18
18
  // src/dogfooding/pr-reviewer-helpers.ts
19
19
  import { randomUUID } from "crypto";
@@ -288,4 +288,4 @@ export {
288
288
  formatReviewComment,
289
289
  createFailedReview
290
290
  };
291
- //# sourceMappingURL=chunk-FKTLAPXJ.js.map
291
+ //# sourceMappingURL=chunk-OCKZ6F5O.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  getRandomProvider,
3
3
  getTimeProvider
4
- } from "./chunk-QJIHSQZX.js";
4
+ } from "./chunk-DBDWMHUL.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-E4IYX7LD.js.map
27
+ //# sourceMappingURL=chunk-ORQAFTAZ.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getErrorMessage
3
- } from "./chunk-QJIHSQZX.js";
3
+ } from "./chunk-DBDWMHUL.js";
4
4
 
5
5
  // src/cli/setup-config.ts
6
6
  import { copyFileSync, existsSync, mkdirSync, writeFileSync } from "fs";
@@ -77,4 +77,4 @@ function ensureBackup(outputPath) {
77
77
  export {
78
78
  runConfigInitSync
79
79
  };
80
- //# sourceMappingURL=chunk-QLRH6KOT.js.map
80
+ //# sourceMappingURL=chunk-OU2NQVKD.js.map
@@ -3,7 +3,7 @@ import {
3
3
  MODEL_IDS,
4
4
  getTimeProvider,
5
5
  resolveModelIdentitySync
6
- } from "./chunk-QJIHSQZX.js";
6
+ } from "./chunk-DBDWMHUL.js";
7
7
 
8
8
  // src/config/model-availability.ts
9
9
  var DEFAULT_TTL_MS = 6e4;
@@ -150,4 +150,4 @@ export {
150
150
  resetAvailabilityCache,
151
151
  filterAvailableModels
152
152
  };
153
- //# sourceMappingURL=chunk-7BONPRR2.js.map
153
+ //# sourceMappingURL=chunk-PFBV5FCT.js.map
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  resolveToken
3
- } from "./chunk-ZQEQVCIU.js";
3
+ } from "./chunk-MY52DFXC.js";
4
4
  import {
5
5
  REGISTRY_PATH,
6
6
  getProjectRoot,
7
7
  loadPapersRegistry,
8
8
  loadTechniquesRegistry,
9
9
  savePapersRegistry
10
- } from "./chunk-2CLFX73Y.js";
10
+ } from "./chunk-B26FGLIJ.js";
11
11
  import {
12
12
  getToolMemory
13
- } from "./chunk-GYDO2WOR.js";
13
+ } from "./chunk-33MFMXBQ.js";
14
14
  import {
15
15
  resolveInsideRoot
16
16
  } from "./chunk-NUBSJGQZ.js";
@@ -27,11 +27,11 @@ import {
27
27
  getOutcomeStore,
28
28
  getTimeProvider,
29
29
  registerPersistentDistillerFactory
30
- } from "./chunk-QJIHSQZX.js";
30
+ } from "./chunk-DBDWMHUL.js";
31
31
  import {
32
32
  ensureLearningDir,
33
33
  getRulesFile
34
- } from "./chunk-RUSP5PJR.js";
34
+ } from "./chunk-GZ4NF4ZW.js";
35
35
 
36
36
  // src/learning/strategy-distiller-persistence.ts
37
37
  import { writeFileSync, readFileSync, renameSync, unlinkSync, existsSync } from "fs";
@@ -2686,4 +2686,4 @@ export {
2686
2686
  summarizeContextForPrompt,
2687
2687
  getContextPromptPrefix
2688
2688
  };
2689
- //# sourceMappingURL=chunk-S4U3Z6ZS.js.map
2689
+ //# sourceMappingURL=chunk-QZUT22LP.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  loadPapersRegistry
3
- } from "./chunk-2CLFX73Y.js";
3
+ } from "./chunk-B26FGLIJ.js";
4
4
  import {
5
5
  getErrorMessage
6
- } from "./chunk-QJIHSQZX.js";
6
+ } from "./chunk-DBDWMHUL.js";
7
7
 
8
8
  // src/cli/research-helpers-synthesize.ts
9
9
  import { z } from "zod";
@@ -876,4 +876,4 @@ export {
876
876
  AttributedInsightSchema,
877
877
  synthesizeResearch
878
878
  };
879
- //# sourceMappingURL=chunk-EFDXX5MC.js.map
879
+ //# sourceMappingURL=chunk-UDB5NHJI.js.map